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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With