在python中导入外部“.txt”文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30768056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:56:53  来源:igfitidea点击:

importing external ".txt" file in python

pythonfileimport

提问by Daniyal Durrani

I am trying to import a text with a list about 10 words.

我正在尝试导入一个包含大约 10 个单词的列表的文本。

import words.txt

That doesn't work... Anyway, Can I import the file without this showing up?

那不起作用...无论如何,我可以在不显示此文件的情况下导入文件吗?

Traceback (most recent call last):
File "D:/python/p1.py", line 9, in <module>
import words.txt
ImportError: No module named 'words'

Any sort of help is appreciated.

任何形式的帮助表示赞赏。

回答by farhawa

As you can't import a .txt file, I would suggest to read words this way.

由于您无法导入 .txt 文件,我建议您以这种方式阅读单词。

list_ = open("world.txt").read().split()

回答by abrarisme

Importgives you access to other modules in your program. You can't decide to import a text file. If you want to read from a file that's in the same directory, you can look at this. Here's another StackOverflow postabout it.

导入使您可以访问程序中的其他模块。您无法决定导入文本文件。如果要从同一目录中的文件读取,可以查看. 这是另一篇关于它的 StackOverflow帖子

回答by user1668844

The "import" keyword is for attaching python definitions that are created external to the current python program. So in your case, where you just want to read a file with some text in it, use:

“import”关键字用于附加在当前 python 程序外部创建的 python 定义。因此,在您的情况下,您只想读取包含一些文本的文件,请使用:

text = open("words.txt", "rb").read()

text = open("words.txt", "rb").read()

回答by No Spoko

You can import modules but not text files. If you want to print the content do the following:

您可以导入模块,但不能导入文本文件。如果要打印内容,请执行以下操作:

Open a text file for reading:

打开一个文本文件进行阅读:

f = open('words.txt', 'r')

Store content in a variable:

将内容存储在变量中:

content = f.read()

Print content of this file:

打印此文件的内容:

print(content)

After you're done close a file:

完成后关闭文件:

f.close()

回答by mr_orange

numpy's genfromtxt or loadtxt is what I use:

numpy 的 genfromtxt 或 loadtxt 是我使用的:

import numpy as np
...
wordset = np.genfromtxt(fname='words.txt')

Thisgot me headed in the right direction and solved my problem.

让我朝着正确的方向前进并解决了我的问题。