1

Hello I have several txt files in a directory, I would like to apply the following python function to all my txt files:

file = open('folder/testing.txt', 'r',encoding='utf-8') 
list_lines = []   
for line in file: 
    list_lines.append(line.replace('-\n', ' '))
list_lines2 = []    
for line in list_lines:
    list_lines2.append(line.replace('-\n', ''))
list_lines3 = []
for line in list_lines2:
    list_lines3.append(line.replace('\n', ''))
big_line = ''.join(list_lines3)
text_file=`open("folder/Output.txt", "w")`
print(big_line)
text_file.write(big_line)
text_file.close()
print('writing document')

In order to achieve this I tried making a function:

def change(document,encoding):
    file = open(document, 'r',encoding=encoding) 
    list_lines = []   
    for line in file: 
        #print(line.replace('\n', ' ').replace('\r', ''))
        list_lines.append(line.replace('-\n', ' '))
    list_lines2 = []    
    for line in list_lines:
        list_lines2.append(line.replace('-\n', ''))
    list_lines3 = []
    for line in list_lines2:
        list_lines3.append(line.replace('\n', ''))
    big_line = ''.join(list_lines3)
    text_file = open(document+'changed', "w")
    print(big_line)
    text_file.write(big_line)
    text_file.close()
    print('writing document')    

In fact my function works very well however I have a directory like this:

folder$ ls

file1.txt file2.txt file3.txt ... fileN.txt

So I would like to appreciate support to find a way to apply my funcion to all the documents in the directory all end with the txt extention thanks for the support

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
neo33
  • 1,809
  • 5
  • 18
  • 41

1 Answers1

1

Applying your change function to every file ending with ".txt" in the current directory is pretty easy with glob:

import glob

for file in glob.glob("*.txt"):
    change(file, "utf-8")

Although this was not the question, I cannot look at this code without suggesting this shorter version of change:

def change(document,encoding):
    with open(document, 'r',encoding=encoding) as file:
        list_lines = [line.replace('-\n', ' ').replace('\n', '') for line in file]   
    big_line = ''.join(list_lines)
    print(big_line)
    with open(document+'changed', "w") as text_file:
        text_file.write(big_line)
    print('writing document')    
BurningKarl
  • 1,176
  • 9
  • 12