简体   繁体   English

Python无法在同一目录中打开文件

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

I've met the strange behavior of my python after windows re-installation.重新安装 Windows 后,我遇到了 python 的奇怪行为。 python cant find and open text file in the same directory as running script! python无法在与运行脚本相同的目录中找到并打开文本文件! why?.为什么?。 I'm using python for many years and never had something like that.我使用 python 很多年了,从来没有这样的东西。 Now my old scripts which were worked fine before with file open not working at all.现在,我以前在文件打开时运行良好的旧脚本根本不起作用。 I dont want to fix them al.我不想修复它们。 I want to know what is the issue.我想知道是什么问题。 I have all of the python paths in my environment variables.我的环境变量中有所有的 python 路径。 So the code is just simple and I try to run script from C:\\untitled and txt file is also there.所以代码很简单,我尝试从 C:\\untitled 运行脚本,txt 文件也在那里。

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

So I'm receiving the following output:所以我收到以下输出:

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'

So what can be the problem?那么问题出在哪里呢? How to fix it?如何解决? Ive never met the issue like this.我从来没有遇到过这样的问题。

The code you wrote opens the file in read mode by default.您编写的代码默认以读取模式打开文件。 But we haven't specified how to print to python, try to print the file as below.但是我们没有指定如何打印到python,尝试打印如下文件。

import os

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

Cheers干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM