Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get python to open an outside file?

I am writing a program for class that opens a file, counts the words, returns the number of words, and closes. I understand how to do everything excpet get the file to open and display the text This is what I have so far:

    fname = open("C:\Python32\getty.txt") 
    file = open(fname, 'r')
    data = file.read()
    print(data)

The error I'm getting is:

    TypeError: invalid file: <_io.TextIOWrapper name='C:\\Python32\\getty.txt' mode='r'
    encoding='cp1252'>

The file is saved in the correct place and I have checked spelling, etc. I am using pycharm to work on this and the file that I am trying to open is in notepad.

like image 968
user1778938 Avatar asked Oct 27 '12 07:10

user1778938


People also ask

How do I open an external file in Python?

Opening Files in PythonPython has a built-in open() function to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly. We can specify the mode while opening a file. In mode, we specify whether we want to read r , write w or append a to the file.

How do you access the outside folder in Python?

Method 1: Using sys. The sys. path variable of the module sys contains the list of all directories in which python will search for a module to import. We can directly call this method to see the directories it contains. So for importing mod.py in main.py we will append the path of mod.py in sys.

How do I get Python to read a file?

To read a text file in Python, you follow these steps: First, open a text file for reading by using the open() function. Second, read text from the text file using the file read() , readline() , or readlines() method of the file object. Third, close the file using the file close() method.


1 Answers

You're using open() twice, so you've actually already opened the file, and then you attempt to open the already opened file object... change your code to:

fname = "C:\\Python32\\getty.txt"
infile = open(fname, 'r')
data = infile.read()
print(data)

The TypeError is saying that it cannot open type _io.TextIOWrapper which is what open() returns when opening a file.


Edit: You should really be handling files like so:

with open(r"C:\Python32\getty.txt", 'r') as infile:
    data = infile.read()
    print(data)

because when the with statement block is finished, it will handle file closing for you, which is very nice. The r before the string will prevent python from interpreting it, leaving it exactly how you formed it.

like image 52
Serdalis Avatar answered Oct 13 '22 07:10

Serdalis