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