python 读取txt文件没读到400行,从Python文本文件中读取 - 第一行被错过

I have a file called test which has the contents:

a

b

c

d

e

f

g

I am using the following python code to read this file line by line and print it out:

with open('test.txt') as x:

for line in x:

print(x.read())

The result of this is to print out the contents of the text file except for the first line, i.e. the result is:

b

c

d

e

f

g

Does anyone have any idea why it might be missing the first line of the file?

解决方案

Because for line in x iterates through every line.

with open('test.txt') as x:

for line in x:

# By this point, line is set to the first line

# the file cursor has advanced just past the first line

print(x.read())

# the above prints everything after the first line

# file cursor reaches EOF, no more lines to iterate in for loop

Perhaps you meant:

with open('test.txt') as x:

print(x.read())

to print it all at once, or:

with open('test.txt') as x:

for line in x:

print line.rstrip()

to print it line by line. The latter is recommended since you don't need to load the whole contents of the file into memory at once.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值