简体   繁体   中英

Search for specific word in text file

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:)

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)

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)    

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)

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:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM