簡體   English   中英

Python IOError:[Errno 13]權限被拒絕

[英]Python IOError: [Errno 13] Permission denied

使用下面的代碼,我收到IOError: [Errno 13] Permission denied ,我知道這是由於輸出目錄是輸入目錄的子文件夾:

import datetime
import os

inputdir = "C:\\temp2\\CSV\\"
outputdir = "C:\\temp2\\CSV\\output\\"
keyword = "KEYWORD"

for path, dirs, files in os.walk(os.path.abspath(inputdir)):
    for f in os.listdir(inputdir):
        file_path = os.path.join(inputdir, f)
        out_file = os.path.join(outputdir, f)
        with open(file_path, "r") as fh, open(out_file, "w") as fo:
            for line in fh:
                if keyword not in line:
                    fo.write(line)

但是,當我將輸出文件夾更改為: outputdir = "C:\\\\temp2\\\\output\\\\" ,代碼將成功運行。 我希望能夠將修改后的文件寫入輸入目錄的子文件夾。 在沒有出現“權限被拒絕”錯誤的情況下,我該怎么辦? tempfile模塊在這種情況下會有用嗎?

os.listdir將返回目錄以及文件名。 outputinputdir因此with試圖打開一個目錄進行讀取/寫入。

您到底想做什么? path, dirs, files甚至都沒有在遞歸os.walk

編輯:我認為您正在尋找這樣的東西:

import os

INPUTDIR= "c:\\temp2\\CSV"
OUTPUTDIR = "c:\\temp2\\CSV\\output"
keyword = "KEYWORD"

def make_path(p):
    '''Makes sure directory components of p exist.'''
    try:
        os.makedirs(p)
    except OSError:
        pass

def dest_path(p):
    '''Determines relative path of p to INPUTDIR,
       and generates a matching path on OUTPUTDIR.
    '''
    path = os.path.relpath(p,INPUTDIR)
    return os.path.join(OUTPUTDIR,path)

make_path(OUTPUTDIR)

for path, dirs, files in os.walk(INPUTDIR):
    for d in dirs:
        dir_path = os.path.join(path,d)
        # Handle case of OUTPUTDIR inside INPUTDIR
        if dir_path == OUTPUTDIR:
            dirs.remove(d)
            continue
        make_path(dest_path(dir_path))    
    for f in files:
        file_path = os.path.join(path, f)
        out_path = dest_path(file_path)
        with open(file_path, "r") as fh, open(out_path, "w") as fo:
            for line in fh:
                if keyword not in line:
                    fo.write(line)

如果您成功寫入了輸入遍歷目錄之外的輸出目錄,則首先使用與上述相同的代碼將其寫入那里,然后將其移至輸入目錄內的子目錄。 您可以使用os.move

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM