I know this isn't the most concise way of writing this function, but I'm still learning! My goal is to combine all the text files in a given directory into one main text file.
The first time I run this function, everything works perfectly. The new, merged file is saved into the same directory as the original files. When i try to re-run the function, I get an error message!
def merge_files(path):
''' mergers txt files into one main file'''
now = datetime.datetime.now()
date = ("%s_%s_%s_") %(now.month,now.day,now.year)
files_to_merge = os.listdir(path)
merged_file_list = []
counter = 1
for file in files_to_merge:
if file.endswith(".txt"):
with open(path+("file"+str(counter))+".txt","r") as files:
files = files.readlines()
merged_file_list.append(files)
counter = counter + 1
new_list = ("\n").join(["".join(x) for x in merged_file_list])
print (new_list)
with open (path + date + "final.txt" ,"w") as final:
return final.write(new_list)
Here's the error message I get:
IOError: [Errno 2] No such file or directory: '/Users/star/Desktop/udemy/Sample-Files/file4.txt'
I know there's something wrong with the counter but I'm not sure what!