[Answer]-Error: file i/o in python

1👍

try this:

pathh='/home/pooja/Desktop/'      #set the base path       
fo = open("/home/pooja/Desktop/xml.txt")
for i in range(len(count)):     #use len(count)
    file = fo.readline()
    file = file.strip()          #use strip()
    find_root_tags(pathh+file,str1,i) #base path+file
    mylist.append((file,count[i]))   #using 'list' as a variable name is not good

0👍

So if I understand your question, the file /home/pooja/Desktop/xml.txt contains file names, one per line, relative to /home/pooja/Desktop/ and you need to pass the full path name to find_root_tags.

In Python, you can use + to concatenate strings, so you could do something like the following:

files_path = "/home/pooja/Desktop/"

for i in range(len(count)):

    file = fo.readline()
    file = file.rstrip('\n')
    find_root_tags(files_path + file, str1, i) 

    list.append((file,count[i]))

Asides

First, note that I have replaced your count.__len__ with len(count). In Python, magic methods, i.e. methods of the form __xxxx__ are not called directly. They are defined to be called by some other mechanism. For the len method, it is called internally when you use the len() built-in.

Second, note that if you have less lines in xml.txt than len(count), then fo.readline will raise an exception once you have read all the lines of your files. The usual way of reading all the lines of a file in Python is:

my_file = open("/path/to/file", 'r')
for line in my_file:
    # do something with your line

Finally, to make sure your file is closed whatever happens, i.e. even if an exception is raised while you read the file, you can use the with statement.

So in your example, you would do something like:

files_path = "/home/pooja/Desktop/"
with open("/path/to/file", 'r') as my_file:
    for file in my_file:
        file = file.rstrip('\n')
        find_root_tags(files_path + file, str1, i) 

        list.append((file,count[i]))

Leave a comment