How to read CSV file into Python Programming?
So, Here I have given Python Code and CSV file which I was used in Tutorial.
import csv with open("data.txt", "r") as dataFile: dataFileReader = csv.reader(dataFile) dataList =  for row in dataFileReader: if len (row) != 0: dataList = dataList + [row] dataFile.close() print(dataList)
CSV File :
ABC, XYZ, 1, 2, 3 PQR, WXY, 4, 5, 6 DEF, JKL, 7, 8, 9
This Python code is made for a view and imports the comma separated files in python app. Also with this code user can only read this code in the app but They can't write in the file.
Now, Let's start with the first line of the program. So, in this line, i had imported the CSV library. and because of that, we can use functions like CSV file open, close, edit, read, write and etc.
with open("data.txt", "r") as dataFile:
This line has the function called 'open' which will be written 'with'. So, In this function, we have two parameter one is File Path and another one is operation symbol. In above program we have 'data.txt' is as a file name with the path of the file and 'r' is as an operation symbol of 'Read' operation.
After that, I have referred that file with the operation symbol to variable 'dataFile'.
dataFileReader = csv.reader(dataFile)
In this line, I have pass 'dataFile' to the 'csv.reader()' function. Where it'll be read the file with the CSV file format only. And referred to the 'dataFileReader' variable.
dataList =  for row in dataFileReader: if len (row) != 0: dataList = dataList + [row]
In above lines, 'dataList' used as an array with the empty array set. And after that, I was started for loop row by row in the 'dataFileReader' variable's value. And then it will check if row length is non-zero then add that 'row' to 'dataList' array.
And at after the and we have to close the 'dataFile' so for that I have used 'close()' after it.
When this file will close, We have to print that file into our app. So for that, I have simply used the print function for 'dataList' array. and the user will get the output.
[['ABC', ' XYZ', ' 1', ' 2', ' 3'], ['PQR', ' WXY', ' 4', ' 5', ' 6'], ['DEF', ' JKL', ' 7', ' 8', ' 9']]
So, above will be the output of the application. Where you can see app have specifically shown the information of the file with a comma separation.
So, This was all about reading the CSV file in Python Programming. And for writing the CSV file subscribe the page and you'll get notified when it'll upload.
You can find this video tutorial of this as well by following:
If you have any questions and queries, comment us below.