WindowsError:[错误3]系统找不到指定的路径?

2024-04-19 10:22:36 发布

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

我在多个目录中有多个文件。所有这些文件都有相同的名称,我想将这些文件与另一个目录中的一个文件同名。在

import os
import glob   

filenames = [glob.glob(os.path.join(os.path.expanduser('~'),'C:', 'Users' , 'Vishnu' ,'Desktop','Test_folder','Input','*.txt')), glob.glob(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.path.join(os.path.expanduser('~'),'C:', 'Users' , 'Vishnu' , 'Desktop' ,'Test_folder', 'Test_output','{:}.txt'.format(os.path.split(fname)[-1] )), 'a+')
        f.write(line)
        f.close()    #This should take care of the permissions issue

但是得到错误:

^{pr2}$

编辑代码

import os
import glob  

filenames = [glob.glob(os.path.join('C:/Users/Vishnu/Desktop/Test_folder/Input/','*.txt')), glob.glob(os.path.join('C:/Users/Vishnu/Desktop/Test_folder/Output/','*.txt'))]    

for fname in filenames:
    with open(fname).readlines() as all_lines:
        for line in all_lines:
            f = open(r'C:/Users/Vishnu/Desktop/Test_output/{:}'.format(str(fname.split('/')[-1]), 'a')   
            f.write('{:}\n'.format(line)
            f.close()    

错误:

f.write('{:}\n'.format(line)
^
SyntaxError: invalid syntax

Tags: 文件pathtesttxtoslinefolderfname
3条回答

你的道路的某一部分不存在。您使用的是C:\HOME,它与C:\User\HOME不同。在

^{}在文档中说明了以下内容。在

On Windows, HOME and USERPROFILE will be used if set, otherwise a combination of HOMEPATH and HOMEDRIVE will be used. An initial ~user is handled by stripping the last directory component from the created user path derived above.

因此,似乎只有用户名被扩展,而不是整个用户主路径。在

我必须把这件事弄清楚,你的解释我不清楚——我知道如果英语不是你的第一语言,那一定很难。这是我的看法,请让我知道我是否正确地描述了你的问题。在

你有几个文件夹,我将它们称为folder1和{}。在这些文件夹中,有同名的文件,例如folder1\file1.txt和{}。它们将被连接(连接)到第三个文件夹folder3\file1.txt。在

import glob
import os.path

# Alter these to match your folder names
folder1 = 'folder1'
folder2 = 'folder2'
folder3 = 'folder3'

if not os.path.isdir(folder3): 
    os.mkdir(folder3)
    print(folder3, "created")

for fname1 in glob.iglob(os.path.join(folder1, '*.txt')):
    basen = os.path.basename(fname1)
    fname2 = os.path.join(folder2, basen)
    if os.path.isfile(fname2):
        outfname = os.path.join(folder3, basen)
        with open(outfname, 'wb') as outf: 
            with open(fname1, 'rb') as f1:
                outf.write(f1.read())
            with open(fname2, 'rb') as f2:
                outf.write(f2.read())

如果这不是你需要的,请告诉我。在

您可以使用os.makedirs()来确保路径上的每个目录都将被创建(如果它还不存在的话)。在

相关问题 更多 >