Python 2: AttributeError: 'file' object has no attribute 'strip' - python

I have a .txt document called new_data.txt. All data in this document separated by dots. I want to open my file inside python, split it and put inside a list.
output = open('new_data.txt', 'a')
output_list = output.strip().split('.')
But I have an error:
AttributeError: 'file' object has no attribute 'strip'
How can I fix this?
Note: My program is on Python 2

First, you want to open the file in read mode (you have it in append mode)
Then you want to read() the file:
output = open('new_data.txt', 'r') # See the r
output_list = output.read().strip().split('.')
This will get the whole content of the file.
Currently you are working with the file object (hence the error).
Update: Seems like this question has received a lot more views since its initial time. When opening files, the with ... as ... structure should be used like so:
with open('new_data.txt', 'r') as output:
output_list = output.read().strip().split('.')
The advantage of this is that there's no need to explicitly close the file, and if an error ever occurs in the control sequence, python will automatically close the file for you (instead of the file being left open after error)

Related

'int' object not callable when opening a file in python

I am getting what seems to be an odd error when trying to open a file in python. I am simply trying to open a csv:
with open(filename, 'a') as history:
filename is simply a string pointing the file:
filename = file_path + "\\dashboards\\" + csv_file
it is identified as a string in python, but whenever I get to the open statement, it returns:
TypeError}'int' object not callable
That seems odd as it is just a csv file, with a header. Has anyone run across this before?
``
It looks like you may have defined open as a variable somewhere else with an int value. This is causing the error message.

Why does pickle only reads the first line of the file?

I made a program that stores some data into a file with Pickle
Here is what the file looks like:
ÄX
(7836)q.ÄX
(13289)q.ÄX
(0928)q.ÄX
(26)q.ÄX
(7893)q.ÄX
(3883)q.ÄX
(1982)q.ÄX
what it is is not important
but when I try to read it with:
data = pickle.load(open("num.txt", "rb"))
print(data)
this is the output:
(7836)
while the expected result is:
(7836)
(13289)
(0928)
(26)
(7893)
(3883)
(1982)
How do I fix this?
The following is #jsbueno's answer, worked for me.To be found here +more answers.
Pickle serializes a single object at a time, and reads back a single object - the pickled data is recorded in sequence on the file.
If you simply do pickle.load you should be reading the first object serialized into the file (not the last one as you've written).
After unserializing the first object, the file-pointer is at the beggining of the next object - if you simply call pickle.load again, it will read that next object - do that until the end of the file.
objects = []
with (open("myfile", "rb")) as openfile:
while True:
try:
objects.append(pickle.load(openfile))
except EOFError:
break

Write new text data to text file without overwriting the previous data in python

I have a String list that keeps changing with iteration. I want to write the list of elements to a text file. When the list changes, I want to update the text file without overwriting the old data.
I tried doing this using the append method, but I don't know why it is giving me an error each time I run the code.
It gives the following error:
AttributeError: '_io.TextIOWrapper' object has no attribute 'append'
matches = ['Steve', 'Kaira', 'Wokes']
with open('textfile.txt','a') as f:
for match in matches:
f.append(match)
The file object does not have any attribute append is the cause of your error. There is no function called append() for a file object in python. Instead use write() in append mode.
See this link: Python - AttributeError: '_io.TextIOWrapper' object has no attribute 'append'
See this example:
urls = open("urlfile.txt","a")
for image_url in image_urls:
urls.write(image_url + "\n")
urls.close()

AttributeError: 'NoneType' object has no attribute 'read' in python

if __name__ == '__main__':
filename = open('sevi.txt', 'wb')
content = filename.write("Cats are smarter than dogs")
for line in content.read():
match = re.findall('[A-Z]+', line)
print match
filename.close()
I am new to python. I am just opening a file and writing some text into it. Later reading the content find all the characters in it by using regular expression. but I am getting the error as 'NoneType' object has no attribute 'read'. if I use readlines also, I am getting the error.
The file.write() method returns None in Python 2 (in Python 3 it returns the number of bytes written, for a binary file).
If you want to both write and read with the same file you'll need to open that file in w+ mode, and seek back to put the file position back to the start:
with open('sevi.txt', 'w+b') as fileobj:
fileobj.write("Cats are smarter than dogs")
fileobj.seek(0) # move back to the start
for line in fileobj:
match = re.findall('[A-Z]+', line)
print match
Note that looping over the file object can be done directly, producing individual lines.
I made two other changes: I renamed your variable to fileobj; you have a file object, not just the name of the file here. And I used the file object as a context manager, so that it is closed automatically even if any errors occur in the block.
filename.write("Cats are smarter than dogs") is the function that returns None type like every function in Python if it's not specified otherwise with a return statement. So the value of the variable content is None and You are trying to read from that. Try filename.read() instead.
import re
ofile = open('sevi.txt', 'r+')
ofile.write("Cats are smarter than dogs")
ofile.seek(0)
data = ofile.read()
upper = re.findall(r'[A-Z]', data)
print upper
lower = re.findall(r'[a-z]', data)
print lower
ofile.close()

TypeError when performing a .open in python

I am trying to open a text file that I have written data to previously in the script and perform multiple find and replaces. The file is assigned to the variable text_file however I get the error:
Message File Name Line Position Traceback <module C:\temp\download\test.py 41"IOError: [Errno 22] invalid mode ('r') or filename: ""<closed file '20150203-0842.txt', mode 'w' at 0x02D6C5A0>"""
I have tried this both in r and w mode and get the same result. If I remove the str portion of the line I get the error:
"Message File Name LinePosition Traceback<module> C:\temp\download\test.py 41
TypeError: coercing to Unicode: need string or buffer, file found
Code is:
replacelines = open(str(text_file), 'r')
replace = {"u'":'', ' ':'', ']':'', ']':'', "'":''}
for line in replacelines:
for src, target in replacements.iteritems():
line = line.replace(src, target)
replacelines.write(line)
replacelines.close()
The code above is from the SO however I want do not want to create a a separate file I would like this to remain the same file.
open() expects the path to the file as its first argument. You're passing an actual file object. Since some file objects don't even have paths (e.g. io.StringIO), there's no general way to make this work. You need to figure out the path to the file and pass that instead:
replacelines = open('20150203-0842.txt', 'r')
Calling str(text_file) results in a name of <closed file '20150203-0842.txt', mode 'w' at 0x02D6C5A0>, which is an illegal file name. It looks like you expect str(text_file) to give you the file name, but it doesn't. Make sure you have the proper file name before opening the file.
From the second error I can see that text_file is not a string. The first argument of open should be a string containing the path the file, which I don't is the case here.
Just check that, and make sure the (correct) path goes into the first argument and everything is going to work.
If you know that the file in question is a file on disk that you have created, you can retrieve its name from that closed file object you have like this:
>>> f = open('myTestFile.txt', 'w')
>>> f.write("foo\n")
>>> f.close()
>>> f
<closed file 'myTestFile.txt', mode 'w' at 0x1010e26f0>
>>> f.name
'myTestFile.txt'
>>> f2 = open(f.name, 'r')
>>> print f2.read()
foo
In practice (as others here have already said) it's probably a better idea to store the path & file name separately instead of counting on being able to retrieve it from a closed file object.

Categories