python3 在文件確實存在的情況下,運行提示找不到文件


提示 [Errno 2] No such file or directory: 但是路徑下確實存在此文件,在不改動的情況下,再次運行,執行成功。

百思不得其解,看到此鏈接下的回答

http://bbs.csdn.net/topics/391934998?page=1

嘗試使用 os.path.normpath() 替換os.path.join(),先記錄待測試。

-----------------------------------------------------------

使用了以上方法發現並沒有解決問題

 

折騰半天,定位問題在open方法上。

最后得出結論:文件夾名稱最后有個空格,會導致失敗。問題解決!!

待貼代碼。

------------------------------------------------------------------------

錯誤指向這句

shutil.copy(os.path.normpath('%s\%s' % (otherfilepath, file)), outdirname)

通過單步執行定位問題,出錯是在shutil.copy。

下面是shutil.copy源碼
 
        
 1 def copy(src, dst, *, follow_symlinks=True):
 2     """Copy data and mode bits ("cp src dst"). Return the file's destination.
 3 
 4     The destination may be a directory.
 5 
 6     If follow_symlinks is false, symlinks won't be followed. This
 7     resembles GNU's "cp -P src dst".
 8 
 9     If source and destination are the same file, a SameFileError will be
10     raised.
11 
12     """
13     if os.path.isdir(dst):
14         dst = os.path.join(dst, os.path.basename(src))
15     copyfile(src, dst, follow_symlinks=follow_symlinks)  # 定位到的出錯點
16     copymode(src, dst, follow_symlinks=follow_symlinks)
17     return dst
繼續查copyfile的源碼:
 
        
 1 def copyfile(src, dst, *, follow_symlinks=True):
 2     """Copy data from src to dst.
 3 
 4     If follow_symlinks is not set and src is a symbolic link, a new
 5     symlink will be created instead of copying the file it points to.
 6 
 7     """
 8     if _samefile(src, dst):
 9         raise SameFileError("{!r} and {!r} are the same file".format(src, dst))
10 
11     for fn in [src, dst]:
12         try:
13             st = os.stat(fn)
14         except OSError:
15             # File most likely does not exist
16             pass
17         else:
18             # XXX What about other special files? (sockets, devices...)
19             if stat.S_ISFIFO(st.st_mode):
20                 raise SpecialFileError("`%s` is a named pipe" % fn)
21 
22     if not follow_symlinks and os.path.islink(src):
23         os.symlink(os.readlink(src), dst)
24     else:
25         with open(src, 'rb') as fsrc:
26             with open(dst, 'wb') as fdst:  # 最終定位錯誤在這一句
27                 copyfileobj(fsrc, fdst)
28     return dst
 
        

    最后失敗原因是open函數出錯,無法打開dst文件。

根據源碼,執行shutil.copy(srcfile, dstdir),
先是在dstdir文件夾創建一個與srcfile同名的文件路徑os.path.join(dst, os.path.basename(src)),即為dstfile的路徑。
之后執行copyfile,同時打開srcfiledstfile,把srcfile的內容復制到dstfile中。


無意中發現dst的文件夾名最后有個空格,因為dst是由前面的代碼生成的,在生成的時候,文件夾名字字符串最后有個空格‘test ’,實際生成文件夾的時候會自動把最后的空格去掉,即實際文件夾名為test。
而在程序中dstdir的空格還是保留的,即在執行open的時候打開的文件名是 (‘test \\dstfile’),是尋不到文件的(實際存在的是test\\dstfile),因此把空格去掉就不報錯了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM