[英]Python can't open text file: “FileNotFoundError”
我在 Python 3 中打開文本文件時遇到問題:我想打開一個我之前創建的文本文件,它的名稱是“pythontest”。 該文件包含一些數字和單詞。 為了在 Python 中打開它,我這樣做:
with open ('pythontest.txt') as test:
file = test.read()
print(file)
但是 Python 給了我這個錯誤:
FileNotFoundError: [Errno 2] No such file or directory: 'pythontest.txt
如何修復錯誤? 提前致謝。
使用os
模塊檢查您是否在正確的工作目錄中(與您的文本文件相同)。
確保在當前工作目錄中有文本文件
import os
os.getcwd()
確保文件在當前工作目錄中:
import os
os.getcwd()
提供文件的完整路徑。 例如:
with open('c:/Users/joshu/Downloads/ShortSelling.csv') as f:
file = f.read()
print(file)
這將幫助您打開文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.