在python中如何使不同文件夹中的多个文件同名

2024-09-29 02:19:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把来自不同文件夹数据的多个文件合并到一个文件中,但只有相同的文件名是所有文件夹

脚本:

import os

filenames = [os.path.join('C:/Users/Vishnu/Desktop/Test_folder/Input/','*.txt'), os.path.join('C:/Users/Vishnu/Desktop/Test_folder/Output/','*.txt')]
f = open(r'C:/Users/Vishnu/Desktop/Test_output/', 'wb')
for fname in filenames:
    with open(fname) as infile:
        for line in infile:
            f.write(line)

获取错误:

^{pr2}$

修改后

import os
import glob 
import os.mkdir

filenames = [glob.globos(mkdir(os.path.join(os.path.expanduser('~'),'C:', 'Users' , 'Vishnu' ,'Desktop','Test_folder','Input','*.txt'))), glob.glob(os.mkdir(os.path.join(os.path.expanduser('~'),'C:', 'Users' , 'Vishnu' , 'Desktop','Test_folder','Output','*.txt')))]    
filenames[0].extend(filenames[1])
filenames=filenames[0]

if( not os.path.isdir(os.path.join(os.path.expanduser('~'),'C:', 'Users' , 'Vishnu' , 'Desktop' ,'Test_folder', 'Test_output'))):
    os.mkdir(os.path.join(os.path.expanduser('~'),'C:', 'Users' , 'Vishnu' , 'Desktop' ,'Test_folder', 'Test_output'))
for fname in filenames:
    with open(fname) as file:
        for line in file.readlines():
            f = open(os.mkdir(os.path.join(os.path.expanduser('~'), 'Desktop', 'Test_output')),'{:}.txt'.format(os.path.split(fname)[-1] ), 'a+')
            f.write(line)
            f.close()  

Tags: pathtestimporttxtosopenfolderfname
2条回答

首先,您试图打开文件夹本身。其次,我们每次读取文件时都必须关闭它,以避免权限问题

我试过这个密码。现在应该有用了

import os
import glob    #So that * in directory listing can be interpretted as all filenames

filenames = [glob.glob(os.path.join(os.path.expanduser('~'),'Desktop','Test_folder','Input','*.txt')), glob.glob(os.path.join(os.path.expanduser('~'),'Desktop','Test_folder','Output','*.txt'))]    
filenames[0].extend(filenames[1])
filenames=filenames[0]

if( not os.path.isdir(os.path.join(os.path.expanduser('~'), 'Desktop', 'Test_output'))):
    os.mkdir(os.path.join(os.path.expanduser('~'), 'Desktop', 'Test_output'))
for fname in filenames:
    with open(fname) as file:
        for line in file.readlines():
            f = open(os.path.join(os.path.expanduser('~'), 'Desktop', 'Test_output','{:}.txt'.format(os.path.split(fname)[-1] )), 'a+')
            f.write(line)
            f.close()    #This should take care of the permissions issue

据我所知,您在多个目录中有多个文件。其中一些文件具有相同的名称,您需要将这些文件与另一个目录中的一个文件同名。在

第一个任务是找出目录中所有的唯一文件名;并收集这些唯一文件的路径。在

import os, glob
from collections import defaultdict

dirs = [r'/foo/bar/directory_1', r'/foo/bar/directory_2']
file_pattrn = r'*.txt'
unique_files = defaultdict(list)

for d in dirs:
  for i in glob.iglob(os.path.join(d, file_pattrn)):
     unique_files[os.path.basename(i)].append(i)

现在我们有了一个字典,其中键是文件名,值是指向该文件的所有路径的列表。在

一旦我们有了这些文件,我们就遍历它们,创建新文件:

^{pr2}$

相关问题 更多 >