如何阅读.text文件

时间:2014-03-16 18:25:16

标签: python import text-files

我需要你的帮助。我有一个.txt文件,我想用Python 2.7打印所有文本。

我使用了下面显示的代码。但除了错误之外,它没有显示任何文字。

file = open('x.txt' , 'r')
print file.read

现在,该怎么办?

提前感谢你。

4 个答案:

答案 0 :(得分:1)

这样做:

file = open('x.txt', 'r')
file_contents = file.read()
print(file_contents)
file.close()

或者这个:

with open('x.txt', 'r') as file:
    file_contents = file.read()
    print(file_contents)

答案 1 :(得分:1)

with open('foo.txt') as f:
    contents = f.read()
    print(contents)

答案 2 :(得分:0)

使用''将确保文件已关闭。

with open('x.txt', 'r') as f:
    print f.read()

答案 3 :(得分:0)

在操作完成后不关闭文件的公寓我认为您的代码的错误在于您提供给open方法的路径

如果你的文件名确实是“x.txt”,那么下面的代码应该有效:

with open("x.txt","r") as f:
    print file.read()

如果x是变量名,并且您打算在文件路径中替换x的内容,那么您应该这样做:

with open("%s.txt"%(str(x)),"r") as f:
    print file.read()

希望有所帮助! 干杯, 亚历