【问题标题】:Python File not found errorPython 文件未找到错误
【发布时间】:2013-11-04 11:53:34
【问题描述】:

我有一个文件夹,里面有不同的子文件夹。我必须遍历所有文件并检查 John 和 Jose 的出现并分别替换为 Mikel 和 Mourinho。

这是我用 Python 编写的脚本。它工作正常,但是当我遇到.gif 文件时,它给了我一个错误并且它没有进一步迭代。

你能告诉我为什么吗?

错误是

Traceback (most recent call last):
  File "C:\Users\sid\Desktop\script.py", line 33, in <module>
    os.chmod(path ,stat.S_IWRITE)
FileNotFoundError: [WinError 2] The system cannot find the file specified:'C:\Users\sid\Desktop\test\\images/ds_dataobject.gif.bak'

我的代码:

import os,stat
import fileinput
import sys

rootdir ='C:\Users\spemmara\Desktop\test'
searchTerms={"John":"Mikel", "Jose":"Mourinho"}

def replaceAll(file,searchExp,replaceExp):
    for line in fileinput.input(file, inplace=1):
        if searchExp in line:
            line = line.replace(searchExp,replaceExp)
        sys.stdout.write(line)

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        path=subdir+'/'+file
        print(path)
        os.chmod(path ,stat.S_IWRITE)
        for key,value in searchTerms.items():
            replaceAll(path,key,value)
        os.chmod(path,stat.S_IREAD)

【问题讨论】:

    标签: python filenotfoundexception


    【解决方案1】:

    使用原始字符串或双黑斜线\\

    没有\\ 或原始字符串'\t' 被转换为制表符空间:

    >>> print 'C:\Users\spemmara\Desktop\test'
    C:\Users\spemmara\Desktop   est
    

    使用原始字符串:

    >>> print r'C:\Users\spemmara\Desktop\test'
    C:\Users\spemmara\Desktop\test
    

    双黑斜线:

    >>> print 'C:\\Users\\spemmara\\Desktop\\test'
    C:\Users\spemmara\Desktop\test
    

    更新:

    'C:\Users\sid\Desktop\test\images/ds_dataobject.gif.bak'

    查看您尝试将\/ 混合在一个路径中的错误,最好使用os.path.join

    path = os.path.join(subdir, file)
    

    【讨论】:

    • 代码正在运行。它正在用穆里尼奥替换包含 Jose 的文件,但是当有 .gif 文件时,它会给出错误。那么是原始字符串的问题吗
    • 我已经尝试过使用其他文件夹也说,C:\Users\spemmara\Desktop\Source。即使对于这个文件夹,代码也可以工作。正在替换,如果是你提到的问题,那么应该不会报错吧
    • gif 是另一个与 rawstring 无关的问题
    • @Wolf 它适用于'Users\spemmara\Desktop\Source',因为该字符串不包含任何特殊字符,如\t\a
    • @Wolf 不要使用path=subdir+'/'+file,而是使用path = os.path.join(subdir, file)
    【解决方案2】:

    除了 hcwhsa 的答案,您还可以通过使用双反斜杠来努力工作:

    rootdir = 'C:\\Users\\spemmara\\Desktop\\test'
    

    我昨天丢了我的水晶球,但我想还有一件事给你带来麻烦,因为当你的程序找到一个gif 文件时,你正试图向它写入文本。

    如果不想做,就用条件测试一下:

    for subdir, dirs, files in os.walk(rootdir):
        for file in files:
            path=subdir+'/'+file
            print(path)
            os.chmod(path ,stat.S_IWRITE)
            if '.gif' not in path:
                for key,value in searchTerms.items():
                    replaceAll(path,key,value)
            os.chmod(path,stat.S_IREAD)
    

    【讨论】:

      猜你喜欢
      • 2016-06-05
      • 2015-07-01
      • 2019-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      • 2015-03-25
      相关资源
      最近更新 更多