试图在python中读取文件

时间:2013-02-19 17:13:31

标签: python

请任何人帮我阅读python中的.text文件

这是我的代码

flink open(2of12inf.txt, "rU")   

但我收到错误

3 个答案:

答案 0 :(得分:3)

您忘记了=转让声明和引号:

flink = open('2of12inf.txt', "rU")   

最佳做法是将文件作为上下文管理器(with statement)打开,以便自动关闭:

with open('2of12inf.txt', "rU") as flink:
    # do something with the open file object

# flink will be closed automatically.

flinkfile object,因此您可以使用.read().readline()等方法来阅读它。或者你可以遍历对象(迭代)每次获得单行:

with open('2of12inf.txt', "rU") as flink:
    for line in flink:
        # do something with each line.

我使用文件的绝对路径而不是相对路径来避免意外:

with open('/path/to/directory/with/2of12inf.txt', "rU") as flink:

或者您可以使用os.path library构建绝对路径:

import os.path

filename = os.path.expanduser('~/2of12inf.txt')

with open(filename, "rU") as flink:
例如,

在当前用户主目录中打开名为2of12inf.text的文件。

答案 1 :(得分:0)

使用以下示例:

#!/usr/bin/python
# open file
f = open ("/etc/passwd","r")

#Read whole file into data
data = f.read()

# Print it
print data

# Close the file
f.close()

答案 2 :(得分:0)

您应该将文件名括在引号中(并在flink和open之间添加赋值运算符):

flink = open("2of12inf.txt", "rU")

正如IT Ninja所说,我还强烈建议使用with构造来打开文件:

with open("2of12inf.txt", "rU") as flink:
    # do stuff...

这将像处理try-finally块一样关闭文件。