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?
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)
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"])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.