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..

Community
  • 1
  • 1
user2303695
  • 70
  • 1
  • 7

3 Answers3

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.

Pep_8_Guardiola
  • 5,002
  • 1
  • 24
  • 35
0

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

Armin Rigo
  • 12,048
  • 37
  • 48
0

Why don't you try to catch this exception and print out list1[1] to check whether it contains correct filename? I expect it may contain illegal characters. You should probably mangle these strings from second fields of your file before you use it as the filename.

Michał Fita
  • 1,183
  • 1
  • 7
  • 24
  • how can the filename be illegal if it works with the second code that i just posted..!! – user2303695 Jun 13 '13 at 10:19
  • Can be. And it is. Look at the traceback you've posted in comment to the question. The filename used as argument to `open()` is actually "`B003Ai2VGA\n`". If you do not see the problem with the filename, I tell you it is a *new line* character present in it. The second code works only, because it does not iterate through your file. – Michał Fita Jun 13 '13 at 10:51