【问题标题】:How do I get Pycharm to find a file that I want to use in my code?如何让 Pycharm 找到我想在我的代码中使用的文件?
【发布时间】:2016-11-04 11:55:28
【问题描述】:

如何让 Pycharm 找到我想要打开的 .txt 文件?

我正在尝试用一段简单的代码打开一个文件

file_name = "coding_dna.txt"
my_file = open(file_name)
my_file_contents = my_file.read()

打印(我的文件内容)

但我不断收到以下错误

Traceback (most recent call last):
  File "/Users/NicolasSaenz/Bioinformatics/Pybio.py", line 236, in <module>
    my_file = open(file_name)
FileNotFoundError: [Errno 2] No such file or directory: 'coding_dna.txt'

我尝试将 init.py 文件添加到包含该文件的文件夹中,并且我已通过解释器将父文件夹更改为源根文件夹。

folder and subfolders containing file

我确定我可能只是搞砸了一些简单的事情,但我不知道如何让它发挥作用。我将不胜感激。

【问题讨论】:

  • 打印当前工作目录以查看 python 正在执行的位置。 import osprint(os.getcwd())。这将告诉您可以将文件放在哪里,或者您提供完整的文件路径,例如 /home/me/fileC:/Users/me/file
  • 成功了,谢谢你们的帮助!

标签: python macos ide pycharm


【解决方案1】:

可以在运行配置中为您的程序设置工作目录。

只需转到Run - Edit Configurations - Your script configuration 并更新“工作目录”字段。请看下面的截图。

【讨论】:

    【解决方案2】:

    通过导入os 模块,只要我们有正确的路径,我们就可以找到任何文件所在的位置。

    试试下面的代码。

    import os
    
    path = "C:/Users/NicolasSaenz/(The directory where "coding_dna.txt" is in)"
    
    file_name = os.path.join(path, "coding_dna.txt")
    my_file = open(file_name)
    my_file_contents = my_file.read()
    
    print(my_file_contents)
    

    在我的测试脚本中打印时,我得到了您正在寻找的输出。

    希望这有帮助!

    【讨论】:

    • 您可能想检查一下这是否有帮助!
    猜你喜欢
    • 1970-01-01
    • 2021-01-01
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    • 2015-01-27
    • 2015-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多