4

次の内容の test というファイルがあります。

a
b
c
d
e
f
g

次の python コードを使用して、このファイルを 1 行ずつ読み取り、出力します。

with open('test.txt') as x:
    for line in x:
        print(x.read())

この結果、最初の行を除いてテキスト ファイルの内容が出力されます。つまり、結果は次のようになります。

b
c
d
e
f
g 

ファイルの最初の行が欠落している理由を知っている人はいますか?

4

1 に答える 1

8

for line in xすべての行を反復処理するためです。

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

おそらくあなたは次のことを意味しました:

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

すべてを一度に印刷するには、または:

with open('test.txt') as x:
    for line in x:
        print line.rstrip()

行ごとに印刷します。ファイルの内容全体を一度にメモリにロードする必要がないため、後者をお勧めします。

于 2013-06-21T14:13:57.360 に答える