簡體   English   中英

如何打開和讀取多個.txt文件

[英]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.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

我想提示用戶打開目錄,而不要輸入目錄名稱。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM