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

niwlg2el  于 2023-01-03  发布在  Python
关注(0)|答案(3)|浏览(177)

我在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/'
>>>
dly7yett

dly7yett1#

对于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()
r6l8ljro

r6l8ljro2#

您的代码逻辑错误:

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

n9vozmp43#

如果你用的是windows,请以管理员身份重新运行ide。

相关问题