【问题标题】:How to import file in python? [closed]如何在python中导入文件? [关闭]
【发布时间】:2014-10-19 21:20:36
【问题描述】:

如何在 python 中导入文件?现在我正在编写一个文字游戏程序,该程序需要访问包含大量单词的文本文件。如何将此文件(称为 words.txt)导入我的主程序脚本,以便我可以执行诸如从单词列表中搜索特定单词之类的任务?我需要将两个文件保存在同一个文件夹中吗?我尝试过使用不同的命令,例如 inFile,但总是弹出错误消息,我真的不知道是什么问题。

谢谢

更新: 感谢所有的答案。我写了:file = open("hello.txt", 'r'),但它显​​示 'IOError: [Errno 2] No such file or directory: 'hello.txt' '。我做错了什么?我已经将这两个文件保存在文档的同一个文件夹中。

【问题讨论】:

标签: python import word


【解决方案1】:

内置功能“打开”听起来正是您所需要的。此站点上的“读取和写入文件”部分:https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files 值得一读。本质上,您可以像这样使用 open 函数:readFile = open("filename",'r') 并将该文件保存到变量“readFile”中。然后你可以为 readFile 中的每一行做一个 for 循环。如果要写入文件,只需将 r 更改为 w,如果要从文件中读取和写入,则传入 rw。要写入,假设您已经以写入或读取方式打开文件,您只需像这样调用“写入”函数:readFile.write("Things I want to say"),然后将文本保存到 readFile。

【讨论】:

  • 谢谢。我写了:file = open("hello.txt", 'r'),但它显​​示 'IOError: [Errno 2] No such file or directory: 'hello.txt' '。我做错了什么?我已经将这两个文件保存在我的文档中的同一个文件夹中。
  • 我认为“hello.txt”必须与 python 文件位于同一目录中,但最好包含整个路径,如“/Users/you/Desktop/hello.txt "
【解决方案2】:

这样的?

words = []

with open('words.txt','r') as f:
    for line in f:
        for word in line.split():
           words.append(word)

for word in words:
    print word 

抱歉,您想从子文件夹加载 words.txt:

import os

script_path = os.path.dirname(__file__)
relative_path = "textfiles/words.txt"
absolute_path = os.path.join(script_path, relative_path)

words = []

with open(absolute_path,'r') as f:
    for line in f:
        for word in line.split():
           words.append(word)

for word in words:
    print word    

【讨论】:

    猜你喜欢
    • 2013-10-23
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    • 2016-12-15
    • 2012-11-24
    • 2015-10-11
    • 2021-11-15
    相关资源
    最近更新 更多