0

だから、ファイルの各行を含むリストを作成したい

list = open(sys.argv[1]).readlines() #Input File
i=0
print list[i]
for x in list[i]:
    print x  #the problem is on this line
    i+=1

for ループ内の 'print x' は、新しい行にすべてのシンボルを 1 つずつ出力します。行全体を単一のリスト項目として出力する必要があると考えました。なぜこうなった?

4

1 に答える 1

1

Remove the [i] in the for-loop line:

# Don't name a variable 'list' -- it overshadows the built-in
lst = open(sys.argv[1]).readlines()
i=0
print lst[i]
for x in lst:
    print x

Your current code is iterating over the first line of the file, not all of the lines. Remember that i=0 and list is a list of the lines in the file. So, list[i] is the first item in list or, namely, the first line in the file.


Also, your current code isn't going to close the file. Hence, it would be best to use with here:

with open(sys.argv[1]) as myfile:
    lst = myfile.readlines()
    i=0
    print lst[i]
    for x in lst:
        print x

I would strongly recommend that you use with every time you open a file since it auto-closes them for you.

于 2013-11-09T16:05:37.693 に答える