Python: 如何选择文本文件的第一行,以及第二行之后的内容?
我在用Python的时候遇到了一个问题。事情是这样的:我有一个文本文件(textFile1.txt),里面有好几行内容,举个例子:
This is the line 1
This is the line 2
This is the line 3
在我的Python脚本中,我可以把这个文本文件的所有内容都读取出来:
def textFile1(self):
my_file = open("textFile1.txt")
my_file_contents = my_file.read()
return my_file_contents
通过这个函数(read()),我可以把文件里的所有内容都返回。
现在,我想把这些内容写入另一个文本文件,这个文件我会在我的Python程序中再次调用:
The line 1 of my textFile1 is: This is the line 1
The line 2 of my textFile1 is: This is the line 2
The line 3 of my textFile1 is: This is the line 3
但是我现在只能每次写入所有的内容(这很正常,因为我返回的是textFile1.txt的所有内容),我不知道怎么只选择textFile1.txt的第一行,然后是第二行,接着是第三行……
所以总结一下,我的问题是:怎么只选择文本文件中的一行,然后再逐行处理(比如在终端打印出来)?我觉得应该是这样的:
i=0
f = open("textFile.txt","r")
ligne = f.readline()
print ligne[i]
i=i+1
但是在Python中,我不知道怎么做。
谢谢
更新:
感谢大家的回复,但到现在为止,我还是卡在这里。请问,有没有办法用这个函数从文本文件中选择特定的一行:
for line in f:
print line.rstrip() # display all the lines but can I display just the line 1 or 2?
3 个回答
1
你可以一行一行地读取文件。
with open('textFile1.txt') as f:
for line in f:
print line
# Write to the 2nd file textFile2.txt
1
def copy_contents(from_path, to_path):
from_file = open(from_path, 'r')
to_file = open(to_path, 'w')
for no, line in enumerate(from_file.readlines()):
to_file.write('This is line %u of my textFile: %s' % (no, line))
from_file.close()
to_file.close()
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
2
你想要逐行读取文件的内容。文件提供了一种非常简单的方法来做到这一点:
for line in f:
# Do whatever with each line.
需要注意的是,读取的每一行都会包含行末的换行符。
另外,通常最好使用 with
语句来打开文件:
with open('textFile.txt', 'r') as f:
for line in f:
# Do whatever with each line.
这样可以确保在 with
语句结束时,文件会被关闭。即使在出现错误的情况下,也能保证文件会被正确关闭,避免因为某些原因导致文件没有被关闭。