Fix Python – Implementing use of ‘with object() as f’ in custom class in python

I have to open a file-like object in python (it’s a serial connection through /dev/) and then close it. This is done several times in several methods of my class. How I WAS doing it was opening the file in the constructor, and then closing it in the destructor. I’m getting weird errors though and I think it has to do with the garbage collector and….

Fix Python – What is a good way to handle exceptions when trying to read a file in python?

I want to read a .csv file in python.

I don’t know if the file exists.
My current solution is below. It feels sloppy to me because the two separate exception tests are awkwardly juxtaposed.

Is there a prettier way to do it?
import csv
fName = “aFile.csv”

try:
with open(fName, ‘r’) as f:
reader = csv.reader(f)
for row in ….

Fix Python – How to write a multidimensional array to a text file?

In another question, other users offered some help if I could supply the array I was having trouble with. However, I even fail at a basic I/O task, such as writing an array to a file.
Can anyone explain what kind of loop I would need to write a 4x11x14 numpy array to file?
This array consist of four 11 x 14 arrays, so I should format it with a nic….

Fix Python – ValueError : I/O operation on closed file

import csv

with open(‘v.csv’, ‘w’) as csvfile:
cwriter = csv.writer(csvfile, delimiter=’ ‘, quotechar=’|’, quoting=csv.QUOTE_MINIMAL)

for w, c in p.items():
cwriter.writerow(w + c)

Here, p is a dictionary, w and c both are strings.
When I try to write to the file it reports the error:
ValueError: I/O operation on closed file.

….

Fix Python – write() versus writelines() and concatenated strings

So I’m learning Python. I am going through the lessons and ran into a problem where I had to condense a great many target.write() into a single write(), while having a “\n” between each user input variable(the object of write()).
I came up with:
nl = “\n”
lines = line1, nl, line2, nl, line3, nl
textdoc.writelines(lines)

If I try to do:
textdoc.wr….

Fix Python – Get last n lines of a file, similar to tail

I’m writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item at the bottom.
So I need a tail() method that can read n lines from the bottom and support an offset. This is hat I came up with:
def tail(f, n, offset=0):
“””Reads a….

Fix Python – Merge PDF files

Is it possible, using Python, to merge separate PDF files?
Assuming so, I need to extend this a little further. I am hoping to loop through folders in a directory and repeat this procedure.
And I may be pushing my luck, but is it possible to exclude a page that is contained in each of the PDFs (my report generation always creates an extra blank p….