2
with open("movies.txt") as infile:
    for line in infile:
        list1 = [ ]
        for temp in line.split(':'):
            list1.append(temp)
        if (list1[0] == 'product/productId'):
            if(list1[1] != product):
                product = list1[1]
                f1=open(list1[1],'w')
        elif(list1[0] == 'review/text'):
            if (list1[1] != product):
                f1.write(list1[1] + os.linesep)

i keep getting the ioerror which will disappear as soon as i use "for line in filename" instead of "with open(filename) as file:" help please

i have already tried all the solutin on this page Read large text files in Python, line by line without loading it in to memory but to no use

when i use this code it works perfectly fine...

for line in file_contents('movies.txt').splitlines():
    list1 = [ ]
    for temp in line.split(":"):
        list1.append(temp)
    for temp2 in line.split(":"):
        list1.append(temp2)
    if (list1[1] != product):
        if (list1[0] == 'product/productId'):
            product = list1[1]
            f1 = open(list1[1],'w')
        elif(list1[0] == 'review/text'):
            f1.write(list1[1] + os.linesep)

but i have to use the first code that i posted..

4

3 回答 3

3

As you are reading lines from a file, you are getting the trailing new line character \n. You can see this in the Traceback that you posted and I assume that this is where the problem is coming from.

Use .strip() to remove unwanted white space and new line characters before trying to open the file. You may also have to provide the full path to the file you wish to work on rather than just the file name.

于 2013-06-13T10:52:03.877 回答
0

Likely because line1[1] is invalid as a filename, e.g. it is an empty string.

于 2013-06-13T10:07:29.760 回答
0

你为什么不尝试捕捉这个异常并打印出来list1[1]检查它是否包含正确的文件名?我预计它可能包含非法字符。在将其用作文件名之前,您可能应该从文件的第二个字段中删除这些字符串。

于 2013-06-13T10:16:47.313 回答