如何打开和读取多个.txt文件

时间:2019-04-05 15:01:51

标签: python file

这个问题以前曾被朋友问过,但我们没有答案。

我们需要从我的目录中打开和读取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文件的内容。有人可以帮我编码吗?

3 个答案:

答案 0 :(得分:1)

如果要串联{ "destination_addresses": [ "4100 Lake Dr SE Suite 300, Grand Rapids, MI 49546, USA" ], "origin_addresses": [ "94360 Bry-sur-Marne, France" ], "rows": [ { "elements": [ { "status": "ZERO_RESULTS" } ] } ], "status": "OK" } chapter1.txtchapter2.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()

答案 1 :(得分:0)

我想提示用户打开目录,而不要输入目录名称。

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 

这应该可以解决您的“我需要列表中的文件”问题,而不是您的“将文件合并为一个”问题

答案 2 :(得分:0)

您可以使用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条件