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.
Related
I have a piece of code that has been working for a while that uses Python’s DictReader.
The code initializes the csv reader, csv_reader = csv.DictReader(my_csv) and then I access csv_reader.fieldnames. Historically this has been working fine.
However today it started throwing this error iterator should return strings, not bytes (did you open the file in text mode?) when I try to access csv_reader.fieldnames.
csv_reader.__dict__ shows an object with an attribute _fieldnames, and it is empty. I’m not sure why this changed or what I can do to resolve it, any suggestions are welcome.
You might need to specify your file's encoding explicitly:
with (open('my.csv', 'rt', encoding='utf-8')) as file:
I am running following command to get the filename
rep = os.path.basename(path)
print(rep)
It is returning following additional details also which are not required.
23-54-00__CreateKey__TCStatus_Report.html' mode='a+' encoding='cp1252'
Anybody have any idea how to get only filename? Please Help!!!
This looks an awful lot like the output of calling str on a file object:
>>> with open('foo', 'w') as f:
... str(f)
...
"<_io.TextIOWrapper name='foo' mode='w' encoding='UTF-8'>"
My guess is that somehow, the path variable ended up containing a file object instead of the file path. Then, getting its basename just converted the file object to a string using str, generating a representation like the one above, and spat out the portion after the last slash, which would be the tail end of the filename plus the mode and encoding portions.
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.
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)
I'm using the latest GAE default python environment. Both of these give expected results:
isTrue = os.path.exists(path)
numberGreaterThanZero = os.path.getsize(path)
But this:
myStrLen = len(open(path))
Gives this error:
TypeError: object of type 'FakeFile' has no len()
There are no results for that error in Google. Not being able to open files is a real bummer. What am I doing wrong? Why does Python/GAE think my file is fake?
The open function returns an open file, not a string. Open files have no len.
You need to actually read the string from the file, for example with the read method.
contents = open(path).read()
myStrLen = len(contents)
If you don't need the contents, you can also get the file size with os.stat.
myStrLen = os.stat('/tmp/x.py').st_size
FakeFile is just GAE's sandboxed implementation of file.