Python:如何选择文本文件的第一行,以及第二行......?

时间:2014-07-30 11:46:12

标签: python text-files

我在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的第1行,第2行之后和第3行之后......

总而言之,我的问题是:如何只选择一行文本文件,然后再增加它(例如在终端中打印)? 我认为它类似于:

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 个答案:

答案 0 :(得分: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语句完成时关闭文件,即使存在可能导致显式close调用被跳过的异常或延迟引用会导致文件对象的终结器被推迟了。

答案 1 :(得分: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 :(得分:1)

您可以逐行迭代文件

with open('textFile1.txt') as f:
    for line in f:
        print line
        # Write to the 2nd file textFile2.txt