13

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.

Daniyal Durrani
  • 173
  • 1
  • 1
  • 3
  • `import` is used to include library functions. To read files see [this](https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files) – Bhargav Rao Jun 10 '15 at 22:03
  • Did you try Googling "python import"? – TigerhawkT3 Jun 10 '15 at 22:19
  • What do you want to do with the list of words? Do you wish to create a list of the words, or just print them out exactly as they appear in the file? What does the file look like - are the words comma separated, on separate rows, etc.? – vk1011 Jun 10 '15 at 23:07
  • You can't actually do that. If you want to get those words you have to read them into your program. You can see how to do that with [this question](http://stackoverflow.com/questions/16922214/reading-a-text-file-and-splitting-it-into-single-words-in-python). – Anthony Dito Jun 10 '15 at 22:02

6 Answers6

31

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()
No Spoko
  • 311
  • 4
  • 4
  • 2
    `'words.txt'` will open if it's in the same directory as the python file. If you need to grab a file from somewhere else just use it's path name like `'/Users/username/Desktop/sample.txt'` – tyirvine Nov 27 '20 at 20:22
7

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

list_ = open("world.txt").read().split()
farhawa
  • 10,120
  • 16
  • 49
  • 91
3

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()

3

This answer is modified from infrared's answer at Splitting large text file by a delimiter in Python

with open('words.txt') as fp:
    contents = fp.read()
    for entry in contents:
        # do something with entry  
Gwen Au
  • 859
  • 9
  • 10
2

numpy's genfromtxt or loadtxt is what I use:

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

This got me headed in the right direction and solved my problem.

mr_orange
  • 121
  • 1
  • 5
0

Import gives 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 post about it.

Community
  • 1
  • 1
abrarisme
  • 495
  • 1
  • 6
  • 14