create csv file python
Python hosting: Host, run, and code Python in the cloud!
Spreadsheets often export CSV (Comma Separated Values) files because they are a universally accepted standard, easy to read, and write. The structure of a CSV file primarily includes values, delineated by commas, and organized by rows. While the file is commonly referred to as ‘comma-separated value’, it’s possible to use alternative delimiters like the pipe character.
Related Course: Data Analysis with Python Pandas
Creating a CSV File in Python
To construct a CSV file using Python, you can utilize the following code, which leverages the comma as a delimiter.
1 | import csv |
Executing the code will generate a file named persons.csv
, containing the following data:
1 | Name,Profession |
This CSV file can be imported into any compatible software or platform.
Reading a CSV File in Python
Once you’ve crafted a CSV file, Python can be used to read its contents. Below is a simple method to read the file row-by-row.
1 | import csv |
The output will display each row as an individual list:
1 | ['Name', 'Profession'] |
If your goal is to save the CSV content into Python lists, follow the steps below. This method will extract data from the CSV file and store them into separate lists. The header row is omitted since it isn’t data-centric.
1 | import csv |
Here’s the expected output:
1 | ['Derek', 'Steve', 'Paul'] |
Most modern software tools support exporting data in CSV format. To master CSV manipulation in Python, it’s beneficial to create diverse CSV files and experiment with them.
Related Course: Data Analysis with Python Pandas
Leave a Reply:
Hello, I am using version 2.5.4 of Python. My question is why when I try and use the 'open' function like (with open('persons.csv', 'wb') as csc file:). It says there's an error in your program: invalid syntax and has the open highlighted.
Hi Tj, this works in Python 2.7.6. The keyword with became part of Python in versuib 2.6
There are two options make it work on Python 2.5:
Alternative, import the __future__ module:
Hi Frank,
Trying to create a csv file using and write into it shows an error saying:
Type-Error: A byte-like object is required not a 'str'
so I am not clear how can I resolve it if I am interested to enter strings as values into rows.
Thank you in advance
Hi Pavan, are you using Python 3.5.0 by any chance?
str in Python 2 is a byte string, str in Python 3.5 is a unicode string.
In Python 3.5 open the file in 'w' not in 'wb', that will stop that error message. I tested the code below with Python 3.5.0
Hi, as a sugestion to the site (that's outstanding, by the way), you should put a "previous tutorial buttom" at the bottom of the page. Because, when I need to take a break I save the page to my favorite and later return to the point that I stopped, in that case I loose the previous pages that I saw in my browser, making impossible to return to a previous lesson.
Thanks! I'll add the previous button
Hey, there tutorial of Python is amazing .. :) thanks for such a wonderful site man..!!
Instead of using a separate variable rowNr and checking the condition on every iteration, can't we add all the rows including the header, and outside the loop, call names.remove(names[0]) ?
How do you make it not skip a line?
Do you want more data on the same row? Simply add more parameters, as: filewriter.writerow(['name','profession','...','....'])
There is no set (x,y) in the csv file format but there is in some other spreadsheet formats.
When I run this script it prints only on every odd row. I want it to print on row 1,2,3,4, not 1,3,5,7...
Could you post the exact code you are using and open the .csv output in a text editor and post here?
Just to be sure, in the loop put "print(rowNr)". In office be sure to set the delimiter to a comma
I solved the issue with the "lineterminator="\n"" code which I found on some forum. So now it's printing to rows 1,2,3,4 etc.
Now I have a new question. I want to print some strings with commas in it. How do I make it so those strings don't get deliminated midway through and end up in different cells?
Hi Avi, good to hear! The most common method is to change the delimiter from a comma to something else, such as a semicolon or pipe. A second alternative may be to escape the characters, but depending on the office program reading the file this may or may not work.
Thanks for your help.
I am trying to change the deliminator to a semicolon with this code:
However, I'm getting an invalid syntax error. Note, I am using Python 3.4.3 and have not made any changes to csv.py.
Hi Avi, this will work:
Output of cell A1 is: name;profession;age
So now it's all in one column, instead of three.
Hi, set the delimiter to a semicolon ';' in office. If you want to flip the column/row order, you could do this:
I hope I understood correct. Let me know if you have any questions.
Thank you, that works great. I had to Google how to set the delimiter to a semicolon ';' in office. This is how:
"Change the separator in all .csv text files
In Microsoft Windows, click the Start button, and then click Control Panel.
Open the dialog box for changing Regional and Language settings.
Type a new separator in the List separator box.
Click OK twice."
Something is wrong with the 'read and write files' page. It doesn't complete loading and I can't scroll the pages. Then I get an error that the page is not responding and to recover it - which doesn't work either. Please fix.
Frank
Thanks for this. New to Python and haven't programmed for many years. I want to read a multi-row.csv file (float), and I've copied your code into Phycharm.
import csv
# open file
with open('gisp2short.csv', 'rb') as f:
reader = csv.reader(f)
# read file row by row
for row in reader:
print row
I'm getting an error message "SyntaxError: Missing parentheses in call to 'print'".
What am I doing wrong?
TIA
Mat
Hi stewart, which file are you trying to read? There is no scrolling, the data is simply in a variable. To scoll you need a textbox widget
Hi Mat! Change the last line to print(row). Python3 requires brackets to be around the print command.
Great resource. However, when I try to read a cvs file I keep getting
Could not find a part of the path 'C:\Program Files\Rhinoceros 5 (64-bit)\System\artist_song_list\artists-songs-albums-tags.csv'.
Traceback:
line 4, in script
even though I just put the file in Rhino's System. Thoughts?
Thanks Jenna! Try to put the file between quotes or using double slashes: 'C:\\Program Files\\Rhinoceros 5 (64-bit)\\System\\artist_song_list\\artists-songs-albums-tags.csv'. A single slash in Python is used as escape characters, such as \n for newline.
Hi Frank,
He means the https://pythonspot.com/read... page has an error on it.
Great site, btw.
Thanks Scot! I'll look at this asap
Hi Frank. I have some problem for the first program. After running the code. I have a file persons.csv but it looks like this .
Name,Profession
Derek,Software Developer
Steve,Software Developer
Paul,Manager
How can I cancel those empty lines between them? Thanks.
Try to add a comma after your print command. Alternative is print(row.replace("\n",""))
Hi Frank,
Is there a reason the lists are "initialized" twice?
names = []
jobs = []
Hi Kathryn,
Thanks for noticing! It should have been "initialized" only once.