[英]Python: Unable to open and read a file
我對python完全陌生。 我試圖讀取我已經創建的文件但收到以下錯誤
File "C:/Python25/Test scripts/Readfile.py", line 1, in <module>
filename = open('C:\Python25\Test scripts\newfile','r')
IOError: [Errno 2] No such file or directory: 'C:\\Python25\\Test scripts\newfile
我的代碼:
filename = open('C:\Python25\Test scripts\newfile','r')
print filename.read()
我也試過
filename = open('C:\\Python25\\Test scripts\\newfile','r')
print filename.read()
但是我遇到了同樣的錯誤。
嘗試:
fpath = r'C:\Python25\Test scripts\newfile'
if not os.path.exists(fpath):
print 'File does not exist'
return
with open(fpath, 'r') as src:
src.read()
首先驗證該文件是否存在。 然后你打開它。 使用包裝器更有用,它會在您閱讀完后關閉您的文件。 所以你不會被許多打開的描述符所困擾。
我認為您可能遇到此問題,因為您沒有包含完整的文件名。
你應該試試:
filename = open('C:\Python25\Test scripts\newfile.txt','r')
print filename.read()
*此外,如果您在與打開的目標文件相同的位置運行此 python 文件,則無需提供完整目錄,只需調用:
filename = open(newfile.txt
我有同樣的問題。 這就是我做對的方式。
你的代碼:
filename = open('C:\\Python25\\Test scripts\\newfile','r')
print filename.read()
嘗試這個:
with open('C:\\Python25\\Test scripts\\newfile') as myfile:
print(myfile.read())
希望能幫助到你。
我正在使用 VS 代碼。 如果我不使用 dent,它將不適用於打印線。 因此,請嘗試使用正確的格式,然后您就會看到魔力。
with open("mytest.txt") as myfile:
print(myfile.read())
或沒有這樣的格式:
hellofile=open('mytest.txt', 'r')
print(hellofile.read())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.