Far
Far

Reputation: 203

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 ?

Upvotes: 0

Views: 2141

Answers (2)

kezzos
kezzos

Reputation: 3221

The glob module is useful for getting files with similar endings:

import glob

print glob.glob("*.txt")  # Returns a list of all .txt files, with path info

for item in glob.glob("*.txt"):
    temp = []  # Might be useful to use a temp list before overwriting your file
    with open(item, "r") as f:
        for line in f:
            print line  # Do something useful here
            temp.append(line)
    with open(item, "w") as f:
        f.writelines(temp)

Upvotes: 1

Ohad Eytan
Ohad Eytan

Reputation: 8464

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)

Upvotes: 2

Related Questions