简体   繁体   中英

how to open and read multiple .txt files

This question has been asked before by a friend, but we got no answer.

We need to open and read 35 text files with .txt extension from my directory. The purpose of opening and reading these files is to put all the texts into only one file in sequence. The files are enumerated from 1 to 35 (eg Chapter1.txt, Chapter2.txt....Chapter35.txt)

I've tried loop through all the files of my directory opening and reading them to append them a list, but I got always an error message that does not make sense because all the files are in the directory:

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()

I need to create a final file that has the content of all these .txt files included sequentially. Can anyone help me with the coding?

Use following code if you want to concatenate chapter1.txt , chapter2.txt , chapter3.txt ... and so on until 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()

Test:

Enter the path of the files: /Users/nataliaresende/Dropbox/XXX
File1Content File2Content File3Content ... File35Content

I like to prompt the user to open the directory instead of typing in the directory name.

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 

This should solve your "I need the files in a list" problem, but not your "merging files into one" problem

You can use 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')

This is assuming you want all the text files in the specified directory; if not, alter the if condition

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM