简体   繁体   English

如何使用 Python 将文件夹中的 all.txt 文件和 append 其内容读取到 one.txt 文件中?

[英]How to read all .txt files in a folder and append its contents into one .txt file, using Python?

I have a folder with multiple.txt files.我有一个包含多个 .txt 文件的文件夹。 for every.txt file in the folder, I want to take one line of the content and append them in a new.txt file.对于文件夹中的每个 .txt 文件,我想将一行内容和 append 放在一个 new.txt 文件中。 How to do this in Python?如何在 Python 中做到这一点? I'm new to this, also new to publicly asking questions.我对此很陌生,对公开提问也很陌生。 this is all I got.这就是我所得到的。

import os    
Folder = os.listdir('E:\\Project\\tests')   
f = open('outputFile.txt', 'a')   

for file in Folder:   
    file.read()   
    for i in file:   
        f.write(i[1] + '\n')   
f.close()

The problem in your code that you don't open the files to read.您的代码中的问题是您没有打开要阅读的文件。

Try this one:试试这个:

from os import listdir
from os.path import isfile, join 

folder_path = 'E:\\Project\\tests'

# get the full names of all the txt files in your folder   
files = [join(folder_path, f) for f in listdir(folder_path) if isfile(join(folder_path, f)) and f.endswith(".txt")] 

f = open('outputFile.txt', 'a')   

for file in files:   
    line = open(file,"r").readlines()[1] # line will be equal to the second line of the file
    f.write(line + '\n')   
f.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用python和bs4读取和覆盖文件夹中的所有* .txt文件? - How to read and overwrite all *.txt files in a folder with python and bs4? 如何在python中读取文件夹中的txt文件列表 - how to read a list of txt files in a folder in python 如何读取文件夹中的多个.txt 文件并使用 python 写入单个文件? - How to read multiple .txt files in a folder and write into a single file using python? 如何使用python读取特定文件夹中的大量txt文件 - How to read a lot of txt file in specific folder using python Python:如何将两个 .txt 文件合二为一并自行生成其 .txt 文件 - Python: how to combine two .txt files into one and self-generate its .txt file 将所有txt文件的内容合并为一个- Python - consolidated contents of all txt files into one- Python python从文件夹中读取所有文件,并将文件名和其他信息写入txt文件 - python read all files from a folder and write the file name and other info into a txt file Python-长.txt文件的文件夹,在每个.txt文件中搜索各种子字符串,并追加到列表中 - Python - Folder of long .txt files, search through each .txt file for various substrings, append to list 如何从一个文件夹中读取多个txt文件 - How to read multiple txt files from one folder 如何使用python读取.txt文件的内容? - how to read the content of .txt file using python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM