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

时间:2016-10-22 06:50:40

标签: python python-2.7 python-3.x

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

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

但是获得错误:

os.mkdir(os.path.join(os.path.expanduser('~'), 'Desktop', 'Test_output'))
WindowsError: [Error 3] The system cannot find the path specified: 'C:\\HOME\\Desktop\\Test_output'
>>> 

已编辑的代码

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

3 个答案:

答案 0 :(得分:1)

您路径的某些部分不存在。您使用的C:\HOMEC:\User\HOME不同。

os.path.expanduser在文档中说明了以下内容。

  

在Windows上,如果设置将使用HOME和USERPROFILE,否则将使用HOMEPATH和HOMEDRIVE的组合。通过从上面派生的创建的用户路径中剥离最后一个目录组件来处理初始〜用户。

所以似乎只扩展了用户名,而不是整个用户主路径。

答案 1 :(得分:1)

您可以使用os.makedirs()确保创建路径中的每个目录(如果它已经不存在)。

答案 2 :(得分:0)

我必须做到这一点,你的解释并不清楚 - 我知道如果英语不是你的第一语言,那一定很难。这是我看到的方式,如果我正确描述您的问题,请告诉我。

您有几个文件夹,我打算将它们称为folder1folder2。在这些文件夹中,您可以使用相同名称的文件,例如folder1\file1.txtfolder2\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())

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

相关问题