【问题标题】:File operations are not working on atom文件操作不适用于原子
【发布时间】: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


【解决方案1】:

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

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

import os
print (os.getcwd())

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

【讨论】:

    猜你喜欢
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多