-6

请任何人都可以帮我阅读python中的.txt文件

这是我的代码

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

但我收到一个错误

4

3 回答 3

3

您忘记了=赋值语句和引号:

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

最好将文件作为上下文管理器(with语句)打开,以便它自动关闭:

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

# flink will be closed automatically.

flink是一个文件对象,所以你可以使用 , 等方法.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来构造绝对路径:

import os.path

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

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

例如,打开一个2of12inf.text在当前用户主目录中命名的文件。

于 2013-02-19T17:15:29.120 回答
0

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

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

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

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

这将像使用 try-finally 块一样关闭文件。

于 2013-02-19T17:18:19.437 回答
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()
于 2013-02-19T17:16:13.577 回答