Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

importing external ".txt" file in python

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

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.

like image 410
Daniyal Durrani Avatar asked Jun 10 '15 22:06

Daniyal Durrani


Video Answer


3 Answers

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()
like image 100
No Spoko Avatar answered Sep 23 '22 19:09

No Spoko


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

list_ = open("world.txt").read().split()
like image 27
farhawa Avatar answered Sep 23 '22 19:09

farhawa


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:

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

like image 22
user1668844 Avatar answered Sep 20 '22 19:09

user1668844