[英]copy and paste the contents of many txt files to create one big file
I have multiple txt files and I want to copy and paste the contents of each file to create one big file using python.我有多个 txt 文件,我想复制并粘贴每个文件的内容以使用 python 创建一个大文件。 Any help is greatly appreciated.
任何帮助是极大的赞赏。
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.
快速搜索一下,我们应该研究如何使用python获取文件的内容,并将它们放入一个大的。
You can start by create a big file using file in python.您可以首先使用 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!让我们使用 for 循环! 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.您可以通过编写新行或您想要格式化代码来进行更正以使其以您希望的方式打印出来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.