import csv
class CSV:
def __init__(self,title, row=[]):
self.row = row
self.title = title
def create(self):
csvfilename = "{}".format(self.title)
csvFileObj = open(csvfilename, 'w' , encoding='utf-8-sig', newline='')
csvWriterObj = csv.writer(csvFileObj)
csvWriterObj.writerow(self.row)
csvFileObj.close()
def createConsolidate(self):
csvfilename = "{}".format(self.title)
csvFileObj = open(csvfilename, 'w' , encoding='utf-8-sig', newline='')
csvWriterObj = csv.writer(csvFileObj)
for row in self.row:
csvWriterObj.writerow(row)
csvFileObj.close()
def appendConsolidate(self):
csvfilename = "{}".format(self.title)
csvFileObj = open(csvfilename, 'a' , encoding='utf-8-sig', newline='')
csvWriterObj = csv.writer(csvFileObj)
for row in self.row:
csvWriterObj.writerow(row)
csvFileObj.close()
def open(self):.
rowData = []
csvfilename = "{}".format(self.title)
csvFileObj = open(csvfilename, encoding='utf-8-sig')
readerObj = csv.reader(csvFileObj)
for row in readerObj:
rowData.append(row)
return rowData
csvFileObj.close()
It's working but not DRY. It can be easy to make it just a function, but for learning purposes, I used Python classes am not familiar with them.
1 Answer 1
Overview
The code layout is pretty good, and you used meaningful names for the class, and some of the functions and variables.
Syntax error
The code does have a syntax error, but I assume there was a simple copy and paste
issue when you copied the code into the question. The .
does not belong
at the end of this line:
def open(self):.
Documentation
You should add documentation to the top of your file to state the purpose of the code. The PEP 8 style guide recommends that you add docstrings for your methods.
Naming
The open
function name is not very meaningful since all your functions
open a file. It also has the same name as Python built-in function. Choose
a more specific name.
It seems like file_name
would be a better variable name than title
.
DRY
There is no need for every function to have a separate csvfilename
.
Simply use the class variable self.file_name
.
Add a class variable for the same "utf-8-sig"
string used by all functions.
Lint check
pylint identified a few style issues.
Consider using with
for the calls to open
. Then you don't need to
call close
. For example:
def create(self):
with open(self.file_name, "w", encoding="utf-8-sig", newline="") as csvFileObj:
csvWriterObj = csv.writer(csvFileObj)
csvWriterObj.writerow(self.row)
There is inconsistent indentation. PEP-8 recommends 4 spaces per level. You can use the black program to automatically modify the code for you.
PEP-8 also recommends you delete trailing whitespace. Again, black
can be used.
Explore related questions
See similar questions with these tags.