I am trying out the program for writing to a CSV file.
Here's my code:
import csv
#field names
fields = ['Name','Branch','Year']
# data rows of CSV file
rows = [['Stef', 'Multimedia Technology','2'],
['Kani', 'Information Technology', '2'],
['Plazaa', 'Electronics Engineering', '4'],
['Lizzy', 'Computer Science', '4'],
['Reshmi', 'Multimedia Technology', '3'],
['Geetha','Electrical Engineering', '4'],
['Keerti', 'Aeronautical Engineering', '3']]
#writing to csv file
#writing to csv file
with open('records.csv','w') as csvfile:
#creating a csv writer object
csvwriter = csv.writer(csvfile)
#writing the fields
csvwriter.writerow(fields)
# writing the data rows
csvwriter.writerows(rows)
The program runs well. But in the CSV file, there is a blank newline space (without any entries) between each entry. How to eliminate that line in the resultant CSV file?
We have to open a CSV file in write mode and write our data into the file line by line. The following code snippet shows a working implementation of this method. We wrote a single column inside the csvfile.csv with the file.write () function in Python. This method isn’t very user-friendly when it comes to handling CSV files.
I explained simply step by step read csv file without header python. Here, Create a basic example of read csv file skip header python. In this example, we will take one demo.csv file with ID, Name and Email fields. Then, we will use open (), next () and reader () functions to read csv file data without header columns fields.
But in the CSV file, there is a blank newline space (without any entries) between each entry. How to eliminate that line in the resultant CSV file? Show activity on this post.
If each row of the CSV file is a dictionary, you can use the DictWriter class of the csv module to write the dictionary to the CSV file. The example illustrates how to use the DictWriter class to write data to a CSV file:
Recommended implementation per Python3 Documentation.
with open('records.csv','w', newline='') as csvfile:
#creating a csv writer object
csvwriter = csv.writer(csvfile)
#writing the fields
csvwriter.writerow(fields)
# writing the data rows
csvwriter.writerows(rows)
https://docs.python.org/3/library/csv.html#csv.writer
Method 1 So when ever i write csv files spaces between lines are created and when reading the files they create problems for me So here is how i solved it
with open("Location.csv","r") as obj:
reader=csv.reader(obj)
for lines in reader:
try:
print(lines["Code"])
print(lines["Key_num"])
except TypeError:
pass
Method 2 Or even simpler you can use Dictreader works fine without error even if spaces are preset
with open("Location.csv","r") as obj:
reader=csv.DictReader(obj)
for lines in reader:
print(lines["Code"])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With