【发布时间】:2017-01-08 07:54:36
【问题描述】:
我昨天开始学习python,我更习惯使用文件进行输入和输出。因此,我编写了以下代码并从 atom 文本编辑器运行它。但我收到以下错误:
[Errno 2] 没有这样的文件或目录:'input.txt'**。
import sys
def init():
orig_stdin = sys.stdin
orig_stdout = sys.stdout
fin = file('input.txt', 'r')
fout = file('output.txt', 'w')
sys.stdin = fin
sys.stdout = fout
return
init()
x = raw_input()
print(x)
为了检查问题是否仅与 python 有关,我编写了以下 C++ 代码。但是我还是没有输出(这次没有错误消息)。
#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
const int N = 1000005;
int x;
void init(){
scanf("%d",&x);
printf("%d\n",x);
}
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
init();
return 0;
}
这两个代码都可以在 sublime text 编辑器上正常工作。
问题已解决。我有点傻。问题出在工作目录上。
【问题讨论】:
-
我不使用 Atom,但它似乎带有“工作目录”功能。您确定工作目录与包含
input.txt的目录相同吗?见discuss.atom.io/t/newbie-question-changing-working-directory/… -
不相关:重定向标准 io 在程序中 至少不常见而且绝对不是一个好习惯,因为您将永远无法使用标准 shell 重定向。如果你只在测试程序中使用它是可以的,但在实际代码中避免这种反模式......
-
@raganjosh 是的,正如我提到的,它适用于崇高的文本
-
我不明白这有什么关系?
-
要确认工作目录问题只需添加
import osprint(os.getcwd())。然后使用 sublime 和 atom 运行。原因应该很明显......
标签: python c++ atom-editor