如何在Python中导入文件?

-2 投票
2 回答
1017 浏览
提问于 2025-04-28 10:52

我该如何在Python中导入文件呢?现在我正在写一个单词游戏程序,需要访问一个包含很多单词的文本文件。怎么把这个文件(叫做words.txt)导入到我的主程序脚本中,这样我就可以进行一些操作,比如从单词列表中搜索特定的单词?我需要把这两个文件保存在同一个文件夹里吗?我试过用不同的命令,比如inFile,但总是出现错误信息,我也不知道问题出在哪里。

谢谢

更新:谢谢大家的回答。我写了:file = open("hello.txt", 'r'),但是它显示'IOError: [Errno 2] No such file or directory: 'hello.txt' '。我哪里做错了?我已经把这两个文件都保存在我的文档的同一个文件夹里了。

暂无标签

2 个回答

0

像这样吗?

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    
0

内置的“open”函数听起来正是你需要的。这个网站上关于“读取和写入文件”的部分:https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files值得一读。简单来说,你可以这样使用open函数:readFile = open("filename",'r'),这会把文件保存到变量“readFile”里。然后你可以用一个循环来处理readFile中的每一行。如果你想写入文件,只需把'r'改成'w',如果你想同时读取和写入,就用'rw'。要写入文件,假设你已经以写入或读写的方式打开了文件,你只需调用“write”函数,像这样:readFile.write("我想说的话"),这样就会把文本保存到readFile里。

撰写回答