Search code examples
pythontext-filesioerror

How to edit lines of all text files in a directory with python


I would like to edit and replace lines of all .txt files in a directory with python for this purpose I am using the following code:

path = '.../dbfiles'
for filename in os.listdir(path):
for i in os.listdir(path):
    if i.endswith(".txt"): 
        with open(i, 'r') as f_in:
            for line in f_in:
               line=tweet_to_words(line).encode('utf-8')  
               open(i, 'w').write(line)

where tweet_to_words(line) is a predefined function for edition lines of the text file. Although I am not sure if the logic of the code is right!? I am also facing the following error:

IOError: [Errno 2] No such file or directory: 'thirdweek.txt'

but the 'thirdweek.txt' exist in the directory! So my question is to see if the method I am using for editing lines in a file is right or not!? and if so how can I fix the error ?


Solution

  • You should add the base path when you use open:

            with open(path + '/' + i, 'r') as f_in:
    

    the same goes for:

                   open(path + '/' + i, 'w').write(line)