w3resource

Python: Write (without writing separate lines between rows) and read a CSV file with specified delimiter

Python module: Exercise-6 with Solution

Write a Python program to write (without writing separate lines between rows) and read a CSV file with specified delimiter. Use csv.reader

Sample Solution:

Python Code:

import csv     
fw = open("test.csv", "w", newline='')
writer = csv.writer(fw, delimiter = ",")
writer.writerow(["a","b","c"])
writer.writerow(["d","e","f"])
writer.writerow(["g","h","i"])
fw.close()
 
fr = open("test.csv", "r")
csv = csv.reader(fr, delimiter = ",")
for row in csv:
  print(row) 
fr.close()

Sample Output:

['a', 'b', 'c']
['d', 'e', 'f']
['g', 'h', 'i']

Flowchart:

Flowchart: Write (without writing separate lines between rows) and read a CSV file with specified delimiter.

Python Code Editor:


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to skip the headers of a given CSV file.
Next: Write a Python program to write dictionaries and a list of dictionaries to a given CSV file.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

For-else construct useful when searched for something and find it:

# For example assume that I need to search through a list and process each item until a flag item is found and 
# then stop processing. If the flag item is missing then an exception needs to be raised.

for i in mylist:
    if i == theflag:
        break
    process(i)
else:
    raise ValueError("List argument missing terminal flag.")