2014-10-19 79 views
-2

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

感谢

更新: 感谢所有的答案。我写道:file = open(“hello.txt”,'r'),但它显示'IOError:[Errno 2]没有这样的文件或目录:'hello.txt''。我做错了什么?我已将这两个文件保存在我的文档中的相同文件夹中。

+0

可能重复[Python:逐行读取文件到数组](https://stackoverflow.com/questions/3277503/python-read-file-line-by-line-into-array) – 2014-10-19 21:22:19

回答

0

在功能上内置 “打开” 听起来像是你需要什么。本网站的“读写文件”部分: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。

+0

谢谢。我写道:file = open(“hello.txt”,'r'),但它显示'IOError:[Errno 2]没有这样的文件或目录:'hello.txt''。我做错了什么?我已将这两个文件保存在我的文档中的相同文件夹中。 – Physicist 2014-10-20 12:30:00

+0

我认为“hello.txt”必须与python文件位于同一目录中,但最好包含整个路径,如“/Users/you/Desktop/hello.txt” – 2015-07-09 19:06:40

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