fname = "myfile.txt" # Name of file
# 1. Opening, reading and closing file
FILE = open(fname)
for line in FILE:
print(line)
FILE.close()
# 2. Use the 'with' context manager to manage opening/closing
with open(fname) as FILE:
for line in FILE:
print(line)
既然我们想要读入数据,就必须明确地将其添加到变量中
fname = "myfile.txt" # Name of file
# 1. Read data, simple
with open(fname) as FILE:
data = []
for line in FILE:
data.append(line)
# 2. Read data directly into the variable
with open(fname) as FILE:
data = list(FILE)
也许我们想在结尾去掉“换行符”,我们可以通过“去掉”字符'\n'来做到这一点:
fname = "myfile.txt" # Name of file
# 1. Read data and strip 'newlines', simple
with open(fname) as FILE:
data = []
for line in FILE:
data.append( line.rstrip() )
# 2. Read data and strip newlines using `map` function
with open(fname) as FILE:
data = map(str.rstrip, FILE)
最后,我们想得到一些具体的行。我们可以使用一个简单的if语句来实现这一点:
fname = "myfile.txt" # Name of file
readLines = [0, 2, 4] # Lines to be read from file, zero indexed
# 1. Read data from specific lines and strip 'newlines', simple
with open(fname) as FILE:
data = []
for line in FILE:
if idx in readLines:
data.append( line.rstrip() )
# 2. Read data from specific lines and strip newlines using 'list comprehension'
with open(fname) as FILE:
data = [ line.rstrip() for idx, line in enumerate(FILE) if idx in readLines ]
import linecache
line_num = 2
line = linecache.getline("file.txt", line_num)
print(line)
# other operations
linecache.clearcache() # after you finished work with file(-s)
您还可以在打开包装时应用生成器:
line_num = 2
with open("file.txt") as f:
*_, line = (f.readline() for _ in range(line_num))
print(line)
您还可以使用for循环:
line_num = 2
with open("file.txt") as f:
for i, line in enumerate(f):
if i == line_num - 1:
break
else:
line = ""
print(line)
要处理文件,有一个上下文管理器的概念,可以查看它。原因是我们必须记住打开/关闭文件,如下所示:
既然我们想要读入数据,就必须明确地将其添加到变量中
也许我们想在结尾去掉“换行符”,我们可以通过“去掉”字符
'\n'
来做到这一点:最后,我们想得到一些具体的行。我们可以使用一个简单的if语句来实现这一点:
像这样的方法应该会奏效:
有一个^{} 模块可供使用:
您还可以在打开包装时应用生成器:
您还可以使用for循环:
相关问题 更多 >
编程相关推荐