How To Read .txt File
I'm in need of your help. I have a .txt file and I want to print all the texts using Python 2.7. I've used this code which is shown below. But it is not showing any text except err
Solution 1:
withopen('foo.txt') as f:
contents = f.read()
print(contents)
Solution 2:
Do this:
file = open('x.txt', 'r')
file_contents = file.read()
print(file_contents)
file.close()
Or this:
withopen('x.txt', 'r') as file:
file_contents = file.read()
print(file_contents)
Solution 3:
Solution 4:
Appart from not closing the file when the operations finish i think that the error with your code lies in the path you are providing to the open method
if your filename is indeed "x.txt" then the code below should work:
withopen("x.txt","r") as f:
print file.read()
If x is a variable name and you intend to replace the contents of x in the path of the file then you should do this:
withopen("%s.txt"%(str(x)),"r") as f:
print file.read()
Hope that helped! Cheers, Alex
Post a Comment for "How To Read .txt File"