17

私のファイルは、次の内容の「xml.txt」です。

books.xml 
news.xml
mix.xml

readline() 関数を使用すると、すべてのファイルの名前に "\n" が追加されます。これは、xml.txt に含まれるファイルを開きたいため、エラーになります。私はこれを書きました:

fo = open("xml.tx","r")
for i in range(count.__len__()): #here count is one of may arrays that i'm using
    file = fo.readline()
    find_root(file) # here find_root is my own created function not displayed here

このコードの実行時にエラーが発生しました:

IOError: [Errno 2] No such file or directory: 'books.xml\n'
4

8 に答える 8

40

末尾の改行だけを削除するには:

line = line.rstrip('\n')

改行文字を保持する理由readlineは、空の行 (改行がある) とファイルの終わり (空の文字列) を区別できるようにするためです。

于 2012-07-01T07:39:37.977 に答える
16

Pythonで改行区切りファイルを読み取り、改行を破棄するための最良の方法から?

lines = open(filename).read().splitlines()
于 2013-11-03T08:13:51.240 に答える
7

文字列オブジェクトのメソッドを使用して.rstrip()、末尾の空白 (改行を含む) を削除したバージョンを取得できます。

例えば:

find_root(file.rstrip())
于 2012-07-01T07:36:05.423 に答える
1

最後から改行文字を削除するには、次のようなものも使用できます。

for line in file:
   print line[:-1]
于 2013-04-20T21:09:38.507 に答える
1

@Lars Wirzeniusの回答のユースケース:

with open("list.txt", "r") as myfile:
    for lines in myfile:
        lines = lines.rstrip('\n')    # the trick
        try:
            with open(lines) as myFile:
                print "ok"
        except IOError as e:
            print "files does not exist"
于 2015-10-28T16:21:49.987 に答える
1

ファイルにコンテキストマネージャーを使用する方が良いスタイルでありlen()、呼び出す代わりに.__len__()

with open("xml.tx","r") as fo:
    for i in range(len(count)): #here count is one of may arrays that i'm using
        file = next(fo).rstrip("\n")
        find_root(file) # here find_root is my own created function not displayed here
于 2012-07-01T07:45:24.690 に答える