[英]Appending lines to a file, then reading them
我想向文件追加或写入多行。 我相信以下代码会追加一行:
with open(file_path,'a') as file:
file.write('1')
我的第一个问题是,如果我这样做:
with open(file_path,'a') as file:
file.write('1')
file.write('2')
file.write('3')
它将创建具有以下内容的文件吗?
1
2
3
第二个问题-如果以后再做:
with open(file_path,'r') as file:
first = file.read()
second = file.read()
third = file.read()
那会将内容读取到变量中,以便first
为1
, second
为2
,依此类推吗? 如果没有,我该怎么办?
第一个问题的答案是否定的。 您正在编写单个字符。 您将不得不单独阅读它们。
另外,请注意file.read()
返回文件的完整内容。
如果您编写了单个字符,并且想要读取单个字符, file.read()
的结果作为字符串处理。
text = open(file_path).read()
first = text[0]
second = text[1]
third = text[2]
至于第二个问题,您应该编写换行符'\\n'
来终止写入文件的每一行。
with open(file_path, 'w') as out_file:
out_file.write('1\n')
out_file.write('2\n')
out_file.write('3\n')
要读取这些行,可以使用file.readlines()
。
lines = open(file_path).readlines()
first = lines[0] # -> '1\n'
second = lines[1] # -> '2\n'
third = lines[2] # -> '3\n'
如果要在每一行的末尾消除换行符,请使用strip()
,它会丢弃字符串前后的所有空格。 例如:
first = lines[0].strip() # -> '1'
更好的是,您可以使用map
将strip()
应用于每一行。
lines = list(map(str.strip, open(file_path).readlines()))
first = lines[0] # -> '1'
second = lines[1] # -> '2'
third = lines[2] # -> '3'
file.write
simple将传递给它的内容写入文件中指针的位置。 file.write("Hello "); file.write("World!")
file.write("Hello "); file.write("World!")
将产生一个内容为"Hello World!"
的文件"Hello World!"
您可以通过将换行符( "\\n"
)附加到要写入的每个字符串来写整行,也可以使用print
函数的file
关键字参数(我觉得这样会更干净)
with open(file_path, 'a') as f:
print('1', file=f)
print('2', file=f)
print('3', file=f)
注意print
到文件并不总是添加换行符,但默认情况下print
本身会添加换行符! print('1', file=f, end='')
与f.write('1')
file.read()
读取整个文件,而不是一次读取一行。 在这种情况下,您会得到
first == "1\n2\n3"
second == ""
third == ""
这是因为在第一次调用file.read()
,指针被设置为文件的末尾。 随后的调用尝试从指针读取到文件末尾。 由于它们位于同一位置,因此您会得到一个空字符串。 更好的方法是:
with open(file_path, 'r') as f: # `file` is a bad variable name since it shadows the class
lines = f.readlines()
first = lines[0]
second = lines[1]
third = lines[2]
要么:
with open(file_path, 'r') as f:
first, second, third = f.readlines() # fails if there aren't exactly 3 lines
向文件写入多行
这将取决于数据的存储方式。 对于编写单个值,您当前的示例是:
with open(file_path,'a') as file:
file.write('1')
file.write('2')
file.write('3')
该文件将包含以下内容:
123
它也将包含自从打开以追加内容以来的所有内容。 要编写换行符,您必须显式添加这些换行符或使用writelines()
(它需要一个可迭代的)。
另外,我不建议将file
用作对象名称,因为它是关键字,因此从现在开始我将使用f
。
例如,在下面的示例中,您具有使用write()
和显式换行符write()
的值的列表:
my_values = ['1', '2', '3']
with open(file_path,'a') as f:
for value in my_values:
f.write(value + '\n')
但是更好的方法是使用writelines()
。 要添加换行符,您可以通过列表理解将它们加入其中:
my_values = ['1', '2', '3']
with open(file_path,'a') as f:
f.writelines([value + '\n' for value in my_values])
如果要打印一系列数字,则可以使用带range
的for循环(如果使用Python 2.x并打印很多数字,则可以使用xrange
)。
从文件中读取各行
要从文件中读取各行,还可以使用for循环:
my_list = []
with open(file_path,'r') as f:
for line in f:
my_list.append(line.strip()) # strip out newline characters
这样,您可以遍历由for循环返回的文件的各行(或在读取它们时对其进行处理,尤其是在大文件中)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.