Reputation: 77
I have multiple txt files and I want to copy and paste the contents of each file to create one big file using python. Any help is greatly appreciated.
Upvotes: 0
Views: 895
Reputation:
First, we should break down the problem.
You have a bunch of text files
Create a big file from those files
Lets now work with that. Doing a little quick googling, we should look into how to take the contents of files with python, and put them into a big one.
You can start by create a big file using file in python.
big_file = open("my_big_file.txt")
Okay now that that is done, lets think about what programming concepts we could use to look at all of the files we have in a directory, open them, and dump their contents inside of the big file...
Lets use a for loop! But first, we need to figure out how to get the names of the files we have in the directory, into our code.
for file in os.listdir():
# We use context managers for opening files in Python using
# the keyword "with"
with open(file) as f:
big_file.write(f.read())
# Then finally, close the big file we created earlier
big_file.close()
You will notice that the text is pretty hard to read if you look at it as it is filled with newline characters and all sorts of garbage...
You can make corrections to get it to print out the way you want it to by writing new lines or however you want to format your code.
Upvotes: 1