文件操作不适用于原子

File operations are not working on atom

我昨天开始学习python,我更习惯使用文件进行输入和输出。因此,我编写了以下代码,并从 atom 文本编辑器 运行 中编写了它。但我收到以下错误:

[Errno 2] No such file or directory: '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 编辑器上运行良好。

The issue is fixed. I was a bit silly. The problem was with the working directory.

每当您看到错误:[Errno 2] No such file or directory: 'input.txt'当您尝试打开您确定存在的文件时,您应该首先怀疑您当前的工作目录存在问题。

这可以通过以下方式轻松测试:

import os
print (os.getcwd())

除非为每个编辑器正确设置了 cwd,否则代码在一个编辑器中工作的事实不会影响它是否在另一个编辑器中工作。对于 Atom,更改当前工作目录的一种方法是 atom.project.setPath(...) 但其他路由可用 here