Im new to python and Im trying to search a text file for a particular string, then output the whole line which contains that string. However, I want to do this as two separate files. Main file contains the following code;
def searchNoCase():
f = open('text.txt')
for line in f:
if searchWord() in f:
print(line)
else:
print("No result")
f.close()
def searchWord(stuff):
word=stuff
return word
File 2 contains the following code
import main
def bla():
main.searchWord("he")
Im sure this is a simple fix but I cant seem to figure it out. Help would be greatly appreciated
I don't use Python 3 so I need to check exactly what changed with __init__.py but in the meantime, create an empty script with that name in the same directory as the following files.
I've tried to cover a few different topics for you to read up on. For example, the exception handler is basically useless here because input (in Python 3) always returns a string but it's something you would have to worry about.
This is main.py
def search_file(search_word):
# Check we have a string input, otherwise converting to lowercase fails
try:
search_word = search_word.lower()
except AttributeError as e:
print(e)
# Now break out of the function early and give nothing back
return None
# If we didn't fail, the function will keep going
# Use a context manager (with) to open files. It will close them automatically
# once you get out of its block
with open('test.txt', 'r') as infile:
for line in infile:
# Break sentences into words
words = line.split()
# List comprehention to convert them to lowercase
words = [item.lower() for item in words]
if search_word in words:
return line
# If we found the word, we would again have broken out of the function by this point
# and returned that line
return None
This is file1.py
import main
def ask_for_input():
search_term = input('Pick a word: ') # use 'raw_input' in Python 2
check_if_it_exists = main.search_file(search_term)
if check_if_it_exists:
# If our function didn't return None then this is considered True
print(check_if_it_exists)
else:
print('Word not found')
ask_for_input()
Related
def encrypt():
while True:
try:
userinp = input("Please enter the name of a file: ")
file = open(f"{userinp}.txt", "r")
break
except:
print("That File Does Not Exist!")
second = open("encoded.txt", "w")
for line in file:
reverse_word(line)
def reverse_word(line):
data = line.read()
data_1 = data[::-1]
print(data_1)
return data_1
encrypt()
I'm currently supposed to make a program that encrypts a text file in some way, and one method that I'm trying to use is reversing the sequence of the lines in the text file. All of my other functions already made, utilize the "for line in file", where "line" is carried over to each separate function, then changed for the purpose of encryption, but when trying to do the same thing here for reversing the order of the lines in the file, I get an error
"str" object has no attribute "read"
I've tried using the same sequence as I did down below, but instead carrying over the file, which works, but I want to have it so that it can work when I carry over individual lines from the file, as is, with the other functions that I have currently (or more simply put, having this function inside of the for loop).
Any Suggestions? Thanks!
Are you trying to reverse the order of the lines or the order of the words in each line?
Reversing the lines can be done by simply reading the lines and using the built-in reverse function:
lines = fp.readlines()
lines.reverse()
If you're trying to reverse the words (actual words, not just the string of characters in each line) you're going to need to do some regex to match on word boundaries.
Otherwise, simply reversing each line can be done like:
lines = fp.readlines()
for line in lines:
chars = list(line)
chars.reverse()
I think the bug you're referring to is in this function:
def reverse_word(line):
data = line.read()
data_1 = data[::-1]
print(data_1)
return data_1
You don't need to call read() on line because it's already a string; read() is called on file objects in order to turn them into strings. Just do:
def reverse_line(line):
return line[::-1]
and it will reverse the entire line.
If you wanted to reverse the individual words in the line, while keeping them in the same order within the line (e.g. turn "the cat sat on a hat" to "eht tac tas no a tah"), that'd be something like:
def reverse_words(line):
return ' '.join(word[::-1] for word in line.split())
If you wanted to reverse the order of the words but not the words themselves (e.g. turn "the cat sat on a hat" to "hat a on sat cat the"), that would be:
def reverse_word_order(line):
return ' '.join(line.split()[::-1])
I am processing data using Python3 and I need to read a results file that looks like this:
ENERGY_BOUNDS
1.964033E+07 1.733253E+07 1.491825E+07 1.384031E+07 1.161834E+07 1.000000E+07 8.187308E+06 6.703200E+06
6.065307E+06 5.488116E+06 4.493290E+06 3.678794E+06 3.011942E+06 2.465970E+06 2.231302E+06 2.018965E+06
GAMMA_INTERFACE
0
EIGENVALUE
1.219034E+00
I want to search the file for a specific identifier (in this case ENERGY_BOUNDS), begin reading the numeric values after this identifier but not the identifier itself, and stop when I reach the next identifier. However, my problem is that I was using isAlpha to find the next identifier, and some of them contain underscores. Here is my code:
def read_data_from_file(file_name, identifier):
with open(file_name, 'r') as read_obj:
list_of_results = []
# Read all lines in the file one by one
for line in read_obj:
# For each line, check if line contains the string
if identifier in line:
# If yes, read the next line
nextValue = next(read_obj)
while(not nextValue.strip().isalpha()): # Keep on reading until next identifier appears
list_of_results.extend(nextValue.split())
nextValue = next(read_obj)
return(list_of_results)
I think I need to use regex, but I am stuck regarding how to phrase it. Any help would be much appreciated!
take = False
with open('path/to/input') as infile:
for line in input:
if line.strip() == "ENERGY_BOUNDS":
take = True
continue # we don't actually want this line
if all(char.isalpha() or char=="_" for char in line.strip()): # we've hit the next section
take = False
if take:
print(line) # or whatever else you want to do with this line
Here's an option for you.
Just iterate over the file until you hit the identifier.
Then iterate over it in another for loop until the next identifier causes a ValueError.
def read_data_from_file(file_name, identifier):
with open(file_name, 'r') as f:
list_of_results = []
for line in f:
if identifier in line:
break
for line in f:
try:
list_of_results.extend(map(float, line.split()))
except ValueError:
break
return list_of_results
You can use this regex: ^[A-Z]+(?:_[A-Z]+)*$
Additionally, you can modify the regex to match strings of custom length, like this: ^[A-Z]{2,10}+(?:_[A-Z]+)*$, where {2, 10} is {MIN, MAX} length:
You can find this demo here: https://regex101.com/r/9jESAH/35
See this answer for more details.
Here is a simple function to verify a string has alpha, uppercase and lowercase and underscore:
RE_PY_VAR_NAME="^[a-zA-Z_]+$"
def isAlphaUscore(s:str) -> bool:
assert not s is None, "s cannot be None"
return re.search(RE_PY_VAR_NAME, s)
I have been trying to create a program that lets users name, write and save documents, here is what I have come up with so far:
doc_name = str(input("Document Name: "))
end = ""
for line in iter(input, end):
document = "\n".join(iter(input, end))
pass
try:
savefile = open("/home/" +doc_name+ ".txt", "w")
savefile.write(x)
savefile.close()
print("Document - " +doc_name+ "\nSuccessfully saved.\n\n")
except:
print("An error occurred.\nUnable to save document.\n\n")
The 'for loop' I have used was from the following page:
Raw input across multiple lines in Python but I am unsure how to use the input from this loop, so I am able to save it to a textfile.
I need the input in this line of code in the place of x:
savefile.write(x)
I am using Python 3.2.3 for this program (if that helps?).
I would like to know how the user input entered during the for loop can be stored in a varible and then used at some other point in the program.
Thanks.
doc_name = input("Document Name: ") # don't need to cast to str
end = ""
result = [] # I recommend initializing a list for the lines
for line in iter(input, end): # you only need this single input call
result.append(line) # add each line to the list
try:
# using "with" in this manner is guaranteed to close the file at the end
with open("/home/" +doc_name+ ".txt", "w") as savefile:
for line in result: # go through the list of lines
# write each one, ending with a newline character
savefile.write(line + '\n')
except IOError:
print("An error occurred.\nUnable to save document.\n\n")
else: # print this if save succeeded, but it's not something we want to "try"
print("Document - " +doc_name+ "\nSuccessfully saved.\n\n")
You only need to use pass when Python expects statements (such as in an indented block) but you have no statements for it to execute - it's basically a placeholder. The common use is when you want to define your program's functions (e.g., def myfunction(a, b):) but you don't have the actual content for them yet.
I have to define a function names Correct(), which has two parameters. A list of strings to be tested for misspelled words(this parameter will be my file), and my dictionary, which I have already made called mydictionary.
The function should test each word in the first list using the dictionary and the check word() function. correct should return a list of words with all the misspelled words replaced.
For example, correct([‘the’, ‘cheif’, ‘stopped’, ‘the’, ‘theif’]) should return the list [‘‘the’, ‘chief’, ‘stopped’, ‘the’, ‘thief’]
Then I'm supposed to test the function in the main()
import string
# Makes a function to read a file, use empty {} to create an empty dict
# then reads the file by using a for loop
def make_dict():
file = open ("spellingWords.txt")
dictionary = {}
for line in file:
# Splits the lines in the file as the keys and values, and assigning them as
# misspell and spell
misspell, spell = string.split(line.strip())
# Assigns the key to the value
dictionary[misspell] = spell
file.close()
return dictionary
mydictionary = make_dict()
#print mydictionary
# Gets an input from the user
word = raw_input("Enter word")
# Uses the dictionary and the input as the parameters
def check_word(word,mydictionary):
# Uses an if statement to check to see if the misspelled word is in the
# dictionary
if word in mydictionary:
return mydictionary[word]
# If it is not in the dictionary then it will return the word
else:
return word
# Prints the function
print check_word(word,mydictionary)
def main():
file2 = open ("paragraph.txt")
file2.read()
thelist = string.split(file2)
print thelist
def correct(file2,mydictionary):
return thelist
paragraph = string.join(thelist)
print paragraph
main()
All my other functions work besides my Correct() function and my Main() function. It is also giving me the error 'file object has no attribute split'. Can I get help with my mistakes?
so I corrected it and now have for my main function
def main():
file2 = open ("paragraph.txt")
lines = file2.read()
thelist = string.split(lines)
def correct(file2,mydictionary):
while thelist in mydictionary:
return mydictionary[thelist]
paragraph = string.join(thelist)
print correct(file2,mydictionary)
however I am now getting the error 'unhashable type: 'list''
You are not understanding the concept of reading file object. You have to store the value that the method read() returns so that you can use it later.
open simply returns a file object, not the lines of a file. To read spy tuff, you can simply use methods to do things. See the docs
To read the file:
lines = file.read()
# do something with lines - it's a super big string
Also, you don't have to import string, the split() method is already built in with strings.
I am still learner in python. I was not able to find a specific string and insert multiple strings after that string in python. I want to search the line in the file and insert the content of write function
I have tried the following which is inserting at the end of the file.
line = '<abc hij kdkd>'
dataFile = open('C:\\Users\\Malik\\Desktop\\release_0.5\\release_0.5\\5075442.xml', 'a')
dataFile.write('<!--Delivery Date: 02/15/2013-->\n<!--XML Script: 1.0.0.1-->\n')
dataFile.close()
You can use fileinput to modify the same file inplace and re to search for particular pattern
import fileinput,re
def modify_file(file_name,pattern,value=""):
fh=fileinput.input(file_name,inplace=True)
for line in fh:
replacement=value + line
line=re.sub(pattern,replacement,line)
sys.stdout.write(line)
fh.close()
You can call this function something like this:
modify_file("C:\\Users\\Malik\\Desktop\\release_0.5\\release_0.5\\5075442.xml",
"abc..",
"!--Delivery Date:")
Python strings are immutable, which means that you wouldn't actually modify the input string -you would create a new one which has the first part of the input string, then the text you want to insert, then the rest of the input string.
You can use the find method on Python strings to locate the text you're looking for:
def insertAfter(haystack, needle, newText):
""" Inserts 'newText' into 'haystack' right after 'needle'. """
i = haystack.find(needle)
return haystack[:i + len(needle)] + newText + haystack[i + len(needle):]
You could use it like
print insertAfter("Hello World", "lo", " beautiful") # prints 'Hello beautiful world'
Here is a suggestion to deal with files, I suppose the pattern you search is a whole line (there is nothing more on the line than the pattern and the pattern fits on one line).
line = ... # What to match
input_filepath = ... # input full path
output_filepath = ... # output full path (must be different than input)
with open(input_filepath, "r", encoding=encoding) as fin \
open(output_filepath, "w", encoding=encoding) as fout:
pattern_found = False
for theline in fin:
# Write input to output unmodified
fout.write(theline)
# if you want to get rid of spaces
theline = theline.strip()
# Find the matching pattern
if pattern_found is False and theline == line:
# Insert extra data in output file
fout.write(all_data_to_insert)
pattern_found = True
# Final check
if pattern_found is False:
raise RuntimeError("No data was inserted because line was not found")
This code is for Python 3, some modifications may be needed for Python 2, especially the with statement (see contextlib.nested. If your pattern fits in one line but is not the entire line, you may use "theline in line" instead of "theline == line". If your pattern can spread on more than one line, you need a stronger algorithm. :)
To write to the same file, you can write to another file and then move the output file over the input file. I didn't plan to release this code, but I was in the same situation some days ago. So here is a class that insert content in a file between two tags and support writing on the input file: https://gist.github.com/Cilyan/8053594
Frerich Raabe...it worked perfectly for me...good one...thanks!!!
def insertAfter(haystack, needle, newText):
#""" Inserts 'newText' into 'haystack' right after 'needle'. """
i = haystack.find(needle)
return haystack[:i + len(needle)] + newText + haystack[i + len(needle):]
with open(sddraft) as f1:
tf = open("<path to your file>", 'a+')
# Read Lines in the file and replace the required content
for line in f1.readlines():
build = insertAfter(line, "<string to find in your file>", "<new value to be inserted after the string is found in your file>") # inserts value
tf.write(build)
tf.close()
f1.close()
shutil.copy("<path to the source file --> tf>", "<path to the destination where tf needs to be copied with the file name>")
Hope this helps someone:)