Python 在目录上运行简单脚本

Python 在目录上运行简单脚本,python,Python,我做了一个简单的程序来测试这个。它只是查找特定字符串的任何实例,并用新字符串替换它。我要做的是对我的整个目录逐个文件运行这个 def replace(directory, oldData, newData): for file in os.listdir(directory): f = open(file,'r') filedata = f.read() newdata = filedata.replace(oldData,newData)

我做了一个简单的程序来测试这个。它只是查找特定字符串的任何实例,并用新字符串替换它。我要做的是对我的整个目录逐个文件运行这个

def replace(directory, oldData, newData):
    for file in os.listdir(directory):
        f = open(file,'r')
        filedata = f.read()
        newdata = filedata.replace(oldData,newData)
        f = open(file, 'w')
        f.write(newdata)
        f.close()
但我一直收到一条错误消息,告诉我其中一个文件不存在于我的目录中,即使它确实存在。我不明白为什么它会告诉我这些

os.listdir()
返回字符串列表,非常类似于终端命令
ls
。它列出了文件名,但不包括目录名。您需要自己使用
os.path.join()

但是,我不建议将
file
作为变量名,因为它与内置类型冲突。此外,在处理文件时,建议使用
with
块。以下是我的版本:

def replace(directory, oldData, newData):
    for filename in os.listdir(directory):
        filename = os.path.join(directory, filename)
        with open(filename) as open_file:
            filedata = open_file.read()
            newfiledata = filedata.replace(oldData, newData)
            with open(filename, 'w') as write_file:
                f.write(newfiledata)
os.listdir()
返回字符串列表,非常类似于终端命令
ls
。它列出了文件名,但不包括目录名。您需要自己使用
os.path.join()

但是,我不建议将
file
作为变量名,因为它与内置类型冲突。此外,在处理文件时,建议使用
with
块。以下是我的版本:

def replace(directory, oldData, newData):
    for filename in os.listdir(directory):
        filename = os.path.join(directory, filename)
        with open(filename) as open_file:
            filedata = open_file.read()
            newfiledata = filedata.replace(oldData, newData)
            with open(filename, 'w') as write_file:
                f.write(newfiledata)
试着这样做:

def replace(directory, oldData, newData):
    for file in os.listdir(directory):
        f = open(os.path.join(directory, file),'r')
        filedata = f.read()
        newdata = filedata.replace(oldData,newData)
        f = open(os.path.join(directory, file), 'w')
        f.write(newdata)
        f.close()
试着这样做:

def replace(directory, oldData, newData):
    for file in os.listdir(directory):
        f = open(os.path.join(directory, file),'r')
        filedata = f.read()
        newdata = filedata.replace(oldData,newData)
        f = open(os.path.join(directory, file), 'w')
        f.write(newdata)
        f.close()

os.listdir
只返回文件名,没有目录前缀。使用
os.path.join
连接它们。
os.listdir
只返回文件名,它们没有目录前缀。使用
os.path.join
将它们连接起来。