IOError:[Errno 13] python中的权限被拒绝

时间:2016-10-26 05:38:50

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

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

import os
from itertools import chain

paths = (r'C:/Users/Test_folder/Input/', r'C:/Users/Test_folder/Input_2/')
for path, dirs, files in chain.from_iterable(os.walk(path) for path in paths):
    for fname in paths:
        for line in fname:
                f = open(os.path.join(r'C:/Users/Test_folder/Test_output/', os.path.basename(fname)), 'a')
                f.write ('{:}\n'.format(line))
                f.close()

错误:

f = open(os.path.join(r'C:/Users/Test_folder/Test_output/', os.path.basename(fname)), 'a')
IOError: [Errno 13] Permission denied: 'C:/Users/Test_folder/Test_output/'
>>> 

2 个答案:

答案 0 :(得分:0)

关于permisson denied

的问题
  with open(os.path.join('type filename here' , os.path.basename(line)), 'w')

或者

for filename in os.listdir(src):
   path = os.path.join(src, filename)
   with open(path, "r") as inputFile:
   content = inputFile.read()

答案 1 :(得分:0)

您的代码逻辑错误:

  • for fname in paths应为for fname in files
  • for line in fname不会逐行读取文件fname,因为fname是字符串,而不是文件对象

权限错误是由于您的代码尝试打开directory以进行追加。

尝试:

import os
from itertools import chain

paths = (r'C:/Users/Test_folder/Input/', r'C:/Users/Test_folder/Input_2/')
for path, dirs, files in chain.from_iterable(os.walk(path) for path in paths):
    for fname in files:
        with open(os.path.join(path, fname)) as fin, open(os.path.join('C:/Users/Test_folder/Test_output/', fname), 'a') as fout:
            fout.write(fin.read())