Reputation:
I am currently trying to search for a specific word in a text file. I've already wrote my code but it seems that the script is not working correctly.
My code:
main_file = open('myfile.txt','w')
x = 'Hello'
x_main = main_file.write(x)
with open('myfile.txt') as f:
datafile = f.readlines()
for line in datafile:
if 'Hello' in line: #I also tried Hello without the quotes
print("ok")
print(x)
I get only Hello as an output and not ok + Hello.
I hope that someone can help me out with this little problem:)
Thank's for every help and suggestion in advance:)
Upvotes: 0
Views: 240
Reputation: 114
Try this one
main_file = open('myfile.txt','w')
x = 'Hello'
x_main = main_file.write(x)
main_file.close()
with open('myfile.txt', 'r') as f:
datafile = f.readlines()
for line in datafile:
if 'Hello' in line: #I also tried Hello without the quotes
print("ok")
print(x)
Upvotes: 2
Reputation: 5889
Your main problem is that you don't close the file after your file after writing to it. Like you have done to open your file with open(file) as file
you can do the same in order to read the file. This way you avoid the hastle of writing file.close()
.
Other than that, your code seems fine.
with open('test.txt','w') as f:
x = 'Hello'
f.write(x)
with open('test.txt') as f:
datafile = f.readlines()
for line in datafile:
if 'Hello' in line: #I also tried Hello without the quotes
print("ok")
print(x)
Upvotes: 2
Reputation: 4670
When writing to your file, you never closed the file (file.close()
). I would suggest using the open()
context manager so you don't have to worry about writing file.close()
.
string = "Hello"
with open("myfile.txt", "w") as file:
file.write(string)
with open("myfile.txt") as file:
lines = file.readlines()
for line in lines:
if "Hello" in line:
print("OK")
print(string)
Upvotes: 0