PyPDF's PdfFileReader() having problems reading file, file not callable - python

So here is my import:
from pyPdf import PdfFileWriter, PdfFileReader
Here is were I write my pdf:
filenamer = filename + '.pdf'
pdf = PdfPages(filenamer)
(great naming convention, I know!)
I write some things to it.
I close it here:
pdf.close()
Here is where I try and read it:
input1 = PdfFileReader(file(filenamer, "rb"))
And here is the error:
Traceback (most recent call last):
File "./datamine.py", line 405, in <module>
input1 = PdfFileReader(file(filenamer, "rb"))
TypeError: 'file' object is not callable
I dont understand the error, because I know the file exists, and when I comment out this line, and subsequent lines to input1, the program runs fine.

It looks like you've assigned an open file to the name file, and then you can't use the builtin any more.

Related

Python Configparser. Whitespace causes AttributeError

I recieve some files with .ini file with them. I have to recieve file names from [FILES] section.
Sometimes there is an extra witespace in another section of .ini-file which raises exception in ConfigParser module
The example of "bad" ini-file:
[LETTER]
SUBJECT=some text
some text
and text with whitespace in the beggining
[FILES]
0=file1.txt
1=file2.doc
My code(Python 3.7):
import configparser
def get_files_from_ini_file(info_file):
ini = configparser.ConfigParser(allow_no_value=True)
ini.read(info_file) # ERROR is here
if ini.has_section("FILES"):
pocket_files = [ini.get("FILES", i) for i in ini.options("FILES")]
return pocket_files
print(get_files_from_ini_file("D:\\bad.ini"))
Traceback (most recent call last):
File "D:/test.py", line 10, in <module>
print(get_files_from_ini_file("D:\\bad.ini"))
File "D:/test.py", line 5, in get_files_from_ini_file
ini.read(info_file) # ERROR
File "C:\Users\ap\AppData\Local\Programs\Python\Python37-32\lib\configparser.py", line 696, in read
self._read(fp, filename)
File "C:\Users\ap\AppData\Local\Programs\Python\Python37-32\lib\configparser.py", line 1054, in _read
cursect[optname].append(value)
AttributeError: 'NoneType' object has no attribute 'append'
I can't influence on files I recieve so that is there any way to ignore this error? In fact I need only [FILES] section to parse.
Have tried empty_lines_in_values=False with no result
May be that's invalid ini file and I should write my own parser?
If you only need the "FILES" part, a simple way is to:
open the file and read into a string
get the part after "[FILES]" using .split() method
add "[FILES]" before the string
use the configparser read_string method on the string
This is a hacky solution but it should work:
import configparser
def get_files_from_ini_file(info_file):
with open(info_file, 'r') as file:
ini_string = file.read()
useful_part = "[FILES]" + ini_string.split("[FILES]")[-1]
ini = configparser.ConfigParser(allow_no_value=True)
ini.read_string(useful_part) # ERROR is here
if ini.has_section("FILES"):
pocket_files = [ini.get("FILES", i) for i in ini.options("FILES")]
return pocket_files
print(get_files_from_ini_file("D:\\bad.ini"))

Import csv module file not opening

I am trying to open a csv file using the csv module and then trying to read some data off of it using this code.
import csv
def file_open():
input_file=str(input('enter the input file to use'))
while True:
try:
with open(input_file,'r') as grades:
grades_reader=csv.reader(grades, delimiter=',')
break
except FileNotFoundError:
print('FileNotFoundError')
input_file=str(input('enter the input file to use'))
row_num=1
for row in grades_reader:
print('row',row_num,row)
row_num+=1
file_open()
and the file opening seems to be working until it gets to the part where it has to read the data and then it gives me an i/o error saying the file is closed. I am quite new to python and would appreciate any insight on what I did wrong.
also input_file is meant to allow the user to pick any file but I will only be using it to call one file called Grades.csv if that information will help
EDIT: traceback error message.
Traceback (most recent call last):
File "C:\Users\musta\OneDrive\Documents\computer assignment programs\program 4\Program4.py", line 24, in <module>
file_open()
File "C:\Users\musta\OneDrive\Documents\computer assignment programs\program 4\Program4.py", line 18, in file_open
for row in grades_reader:
ValueError: I/O operation on closed file.
The file is closed because your break ends the loop, and the with body, therefore closing the file
You should keep that file reading code within the with indentation.
A csv.reader doesn't load the file into some in-memory list

I get the following error AttributeError: __enter__ when only using one with block

When I try to save the file lines in a list I with the following code I get the below error:
Traceback (most recent call last):
File "C:\Users\emiel\AppData\Roaming\Sublime Text 3\Packages\User\Making_a_list_from_file.py", line 7, in <module>
with filename as file_object:
AttributeError: __enter__
This is the code:
with filename as file_object:
lines=file_object.readlines()
for line in lines:
print(line.strip())
The error is telling you that the object you're using in the with statement is not of the right type. __enter__ is one of the methods called as part of the context manager protocol, and the type you're using doesn't have that method.
Based on your variable name, it looks like you may be using a file name where you want to be using a file object. The error message will then make sense, as strings are not context managers the way file objects are. Try changing your with statement to:
with open(filename) as file_object:

Python 3.4.1: Can't Open and Read a local file

def functION():
Source_obj = path.relpath("WebSource\EXAMPLE SOURCE.htm")
data = Source_obj.read()
I am having trouble opening this file while located in a sub-directory directly underneath my Python file... is there a better way to open files from ANY directory on my computer?
FileNotFoundError: [Errno 2] No such file or directory: 'WebSource\\EXAMPLE SOURCE.htm'
I can't read from the file because I get the following error:
C:\python34\python.exe G:\Robot\test.py
Process started >>>
Traceback (most recent call last):
File "G:\Robot\test.py", line 118, in <module>
functION()
File "G:\Robot\test.py", line 64, in functION
data = Source_obj.read()
AttributeError: 'str' object has no attribute 'read'
<<< Process finished. (Exit code 1)
================ READY ================
BTW: The file to be read is just a source file from an HTML Chrome webpage.
EDIT
I'm looking for more help with the path and wondering why I get the first mentioned Traceback regarding the path
os.path.relpath() returns a string, not an open file object. You'll need to open a file first; use the open() function:
def functION():
Source_obj = path.relpath(r"WebSource\EXAMPLE SOURCE.htm")
with open(Source_obj) as fileobj:
data = fileobj.read()
with here treats the file object as a context manager; when the indented codeblock under the statement is exited (either because the code completed or an exception occurred), the file object will automatically be closed.
Your Source_obj is just a string, not a file.
def functION():
Source_obj = path.relpath("WebSource\EXAMPLE SOURCE.htm")
with open(Source_obj) as f:
data = f.read()
By open()-ing it you can read from the file. Using the with context manager, the file will be properly closed for you when you leave that block of code.

How do I save a list to a pickle file in a temporary directory and pass that file into a function?

The issue is that I'm pulling data from one source and I want to save it to dropbox as a pickle file. I can't save it in a directory, because I'm running the code on a server (iron.io).
import tempfile
import pickle
def SFDCDropboxSync(Data):
f = tempfile.NamedTemporaryFile(delete=False)
pickle.dump(Data,open(f,'wb'))
client = dropbox.client.DropboxClient(access_token)
client.put_file(filename, f)
This is the error I get:
Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Shippy/RecurringDataDump/SFDCDropboxUpload.py", line 38, in <module>
if __name__ == "__main__": main() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Shippy/RecurringDataDump/SFDCDropboxUpload.py", line 31, in main
print SFDCDropboxUploadDownload().SFDCDropboxSync(lst) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Shippy/RecurringDataDump/SFDCDropboxUpload.py", line 26, in SFDCDropboxSync
pkl = self.SaveListtoPickle(lst) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Shippy/RecurringDataDump/SFDCDropboxUpload.py", line 20, in SaveListtoPickle
pickle.dump(lst,open(f,'wb')) TypeError: coercing to Unicode: need string or buffer, instance found [Finished in 0.7s with exit code 1] [shell_cmd: python -u "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Shippy/RecurringDataDump/SFDCDropboxUpload.py"] [dir: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Shippy/RecurringDataDump] [path: /usr/bin:/bin:/usr/sbin:/sbin]
In your code, the NamedTemporaryFile f is not a string. It is a file object, similar to the output of open(file_path).
From the documentation: This file-like object can be used in a with statement, just like a normal file.
If you want to path to the created file, use tmp_file.name
For example, this works: (tested on python 3.6.2)
def SFDCDropboxSync(Data):
with tempfile.NamedTemporaryFile() as tmp_file:
pickle.dump(Data, tmp_file)
tmp_file.flush()
print(pickle.load(open(tmp_file.name, 'rb')))
This will delete the file when it exits the while (file closes).
Warning for Windows: you might have trouble reading the file while it is open. Instead, use something similar to this:
with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
pickle.dump(Data, open(tmp_file.name, 'wb'))
tmp_filename = tmp_file.name
pickle.load(open(tmp_filename, 'rb'))
os.remove(tmp_filename)

Categories

Resources