如何使用 Python 读取文件夹中的所有 .txt 文件并将其内容附加到一个 .txt 文件中?
How to read all .txt files in a folder and append its contents into one .txt file, using Python?
我有一个包含多个 .txt 文件的文件夹。
对于文件夹中的每个 .txt 文件,我想获取一行内容并将它们附加到一个新的 .txt 文件中。如何在 Python 中执行此操作?
我是新手,也是公开提问的新手。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()
您的代码中的问题是您没有打开要读取的文件。
试试这个:
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()
我有一个包含多个 .txt 文件的文件夹。 对于文件夹中的每个 .txt 文件,我想获取一行内容并将它们附加到一个新的 .txt 文件中。如何在 Python 中执行此操作? 我是新手,也是公开提问的新手。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()
您的代码中的问题是您没有打开要读取的文件。
试试这个:
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()