python 第一行_Python:如何选择文本文件的第一行,以及第二行……?

本问题已经有最佳答案,请猛点这里访问。

我遇到了一个关于Python的问题。我有一个文本文件(textfile1.txt),有几行例子:

1

2

3This is the line 1

This is the line 2

This is the line 3

我可以在python脚本中以书面形式返回文本文件的所有内容:

1

2

3

4

5

6def textFile1(self):

my_file = open("textFile1.txt")

my_file_contents = my_file.read()

return my_file_contents

使用此函数(read())返回文件的所有内容

现在,我想写另一个文本文件,我用我的python程序再次调用它:

1

2

3The 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行之后……

总而言之,我的问题是:如何选择一个文本文件中的一行,然后增加它(例如在终端中打印)?我想是这样的:

1

2

3

4

5i=0

f = open("textFile.txt","r")

ligne = f.readline()

print ligne[i]

i=i+1

但在Python中,我不知道该怎么做。

谢谢你

更新:

谢谢你的回复,但直到现在,我还是被阻止了。偶然地,是否可以从文本文件中选择一行,尤其是使用此函数:

1

2for line in f:

print line.rstrip() # display all the lines but can I display just the line 1 or 2?

您想循环文件的行。文件提供了一个非常简单的界面:

1

2for line in f:

# Do whatever with each line.

请注意,行将包含任何尾随的换行符。

此外,通常最好在with语句中打开文件:

1

2

3with open('textFile.txt', 'r') as f:

for line in f:

# Do whatever with each line.

这样可以确保在with语句完成时关闭文件,即使存在可能导致跳过显式close调用的异常,或延迟引用,从而导致文件对象的终结器延迟。

您可以一行一行地迭代文件

1

2

3

4with open('textFile1.txt') as f:

for line in f:

print line

# Write to the 2nd file textFile2.txt

1

2

3

4

5

6

7

8

9def 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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值