【问题标题】:how to open and read multiple .txt files如何打开和读取多个 .txt 文件
【发布时间】:2019-04-05 15:01:51
【问题描述】:

之前有朋友问过这个问题,但没有得到答案。

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

【问题讨论】:

  • 正确的路径应该是:with open (os.path,join(files_directory, file)) as x:

标签: python file


【解决方案1】:

如果您想连接chapter1.txtchapter2.txtchapter3.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

【讨论】:

  • 谢谢!问题是文件没有按顺序连接。输出文件的第一章是第12章,不是第01章,有没有可能解决这个问题?
  • 你的意思是文件没有排序?
  • 当程序将所有文本放入文件时,第一个文本不是文本编号 01,而是文本编号 12....输出文件应按照文件 1 的顺序连接所有文本到文件 35...
  • 可以分享文件名吗?
  • 文件名是:chapter1.txt、chapter2.txt、chapter3.txt等等直到chapter35.txt
【解决方案2】:

我喜欢提示用户打开目录而不是输入目录名称。

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 

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

【讨论】:

  • PyQt4 或 PyQt5 也可以,但我认为如果您使用它们,则不需要 [0],因为返回值只是文件名。
【解决方案3】:

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

【讨论】:

  • 回溯(最近一次通话最后):文件“/Users/nataliaresende/Dropbox/PYTHON/join_files2.py”,第 44 行,在 join3() 文件“/Users/nataliaresende/Dropbox /PYTHON/join_files2.py",第 38 行,在 join3 中,open(item, 'r') 为当前:FileNotFoundError: [Errno 2] 没有这样的文件或目录:'Item016.txt'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-04
  • 1970-01-01
  • 2017-06-20
  • 1970-01-01
  • 1970-01-01
  • 2022-06-13
  • 2011-04-17
相关资源
最近更新 更多