[英]how to open and read multiple .txt files
以前有一个朋友问过这个问题,但是我们没有答案。
我们需要从我的目录中打开和读取35个扩展名为.txt
文本文件。 打开和读取这些文件的目的是将所有文本依次放入一个文件中。 文件从1到35枚举(例如Chapter1.txt,Chapter2.txt .... Chapter35.txt)
我尝试遍历目录打开的所有文件并读取它们以将它们追加到列表中,但是我总是收到一条没有意义的错误消息,因为所有文件都在目录中:
Traceback (most recent call last):
File "/Users/nataliaresende/Dropbox/PYTHON/join_files.py", line
27, in <module>
join_texts()
File "/Users/nataliaresende/Dropbox/PYTHON/join_files.py", line
14, in join_texts
with open (file) as x:
FileNotFoundError: [Errno 2] No such file or directory:
'Chapter23.txt'
import sys
import os
from pathlib import Path
def join_texts():
files_list=[]
files_directory = Path(input('Enter the path of the files: '))
for file in os.listdir(files_directory):
for f in file:
with open (file) as x:
y=x.read()
files_list.append(y)
a=' '.join(files_list)
print(a)
join_texts()
我需要创建一个最终文件,该文件具有顺序包含的所有这些.txt文件的内容。 有人可以帮我编码吗?
如果要串联chapter1.txt
, chapter2.txt
, chapter3.txt
...等等,请使用以下代码,直到chapter35.txt
为止:
import os
def joint_texts():
files_directory = input('Enter the path of the files: ')
result = []
for chapter in range(35):
file = os.path.join(files_directory, 'chapter{}.txt'.format(chapter+1))
with open(file, 'r') as f:
result.append(f.read())
print(' '.join(result))
joint_texts()
测试:
Enter the path of the files: /Users/nataliaresende/Dropbox/XXX
File1Content File2Content File3Content ... File35Content
我想提示用户打开目录,而不要输入目录名称。
import os
from PySide import QtGui, QtCore
app = QtGui.QApplication(sys.argv)
first_file = unicode(QtGui.QFileDialog.getOpenFileName()[0])
app.quit()
pathname = first_fname[:(first_fname.rfind('/') + 1)]
file_list = [f for f in os.listdir(pathname) if f.lower().endswith('.txt')]
file_list.sort() #you will need to be careful here - this will do alphabetically so you might need to change chapter1.txt to chapter01.txt etc
这应该可以解决您的“我需要列表中的文件”问题,而不是您的“将文件合并为一个”问题
您可以使用shutil.copyfileobj
:
import os
import shutil
files = [f for f in os.listdir('path/to/files') if '.txt' in f]
with open('output.txt', 'wb') as output:
for item in files:
with open(item, 'rb') as current:
shutil.copyfileobj(current, output)
output.write(b'\n')
假设您希望所有文本文件都位于指定目录中; 如果不是,则更改if条件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.