簡體   English   中英

Python無法在同一目錄中打開文件

[英]Python can't open file in same dir

重新安裝 Windows 后,我遇到了 python 的奇怪行為。 python無法在與運行腳本相同的目錄中找到並打開文本文件! 為什么?。 我使用 python 很多年了,從來沒有這樣的東西。 現在,我以前在文件打開時運行良好的舊腳本根本不起作用。 我不想修復它們。 我想知道是什么問題。 我的環境變量中有所有的 python 路徑。 所以代碼很簡單,我嘗試從 C:\\untitled 運行腳本,txt 文件也在那里。

import os.path
f = open('mytext.txt')
print(f)

所以我收到以下輸出:

Traceback (most recent call last):
  File "c:\untitled\helloworld.py", line 2, in <module>
    f = open('mytext.txt')
FileNotFoundError: [Errno 2] No such file or directory: 'mytext.txt'

那么問題出在哪里呢? 如何解決? 我從來沒有遇到過這樣的問題。

您編寫的代碼默認以讀取模式打開文件。 但是我們沒有指定如何打印到python,嘗試打印如下文件。

import os

f = open('myfile.txt', "r") #open('myfile.txt')
print(f.readline())

干杯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM