To write to CSV in Python, use Python’s csv module.
For example, let's write a list of strings to a new CSV file:
import csv data = ["This", "is", "a", "Test"] with open('example.csv', 'w') as file: writer = csv.writer(file) writer.writerow(data)
Therefore, you will see a file named example.csv in the current folder.
4 steps to write CSV in Python
To write a CSV file in Python:
1. With Open the CSV file in write mode. This happens using the open() function. Give it the path to the file as the first argument. Specify the mode as the second argument ("r" for read, "w" for write).
2. Create a CSV writer object. To do this, create a writer() object of the csv module and pass the open file as its argument.
3. Write data to CSV file. Use the writerow() function of the writer object to write data to the CSV file.
4. Close the CSV file, using the file's close() method.
Here is an example illustrating this process:
import csv # 1. file = open('test.csv', 'w') # 2. writer = csv.writer(file) # 3. data = ["This", "is", "a", "Test"] writer.writerow(data) # 4. file.close()
This code creates a file named test.csv in the current folder.
If the specified file does not exist, the open() function will open a new file. If so, the existing file is opened.
Shorthand
To reduce the time it takes to write to CSV, open the file using the with statement. This way you don't have to worry about closing the file yourself. with will handle this part automatically.
For example:
import csv # 1. step with open('test.csv', 'w') as file: # 2. step writer = csv.writer(file) # 3. step data = ["This", "is", "a", "Test"] writer.writerow(data)
This will create a new CSV file named test.csv in the current folder and write the list of strings into it.
How to write non-ASCII characters to CSV in Python
By default, you cannot write non-ASCII characters to a CSV file.
To support writing non-ASCII values to a CSV file, specify the character encoding as the third parameter in the open() call.
with open('PATH_TO_FILE.csv', 'w', encoding="UTF8")
The rest of the process follows the steps you learned earlier.
How to create headers for CSV files
So far, you have created CSV files that lack structure.
In Python, you can write headers for any CSV file using the
writerow() function for writing any data to CSV.
Example: Let’s create a sample CSV file containing student data.
In order to effectively build the data, you need to create a header for students at the beginning of the CSV file and insert it. You can follow the same steps as before to write the data to a CSV file and you're done.
Here is the code:
import csv # Define the structure of the data student_header = ['name', 'age', 'major', 'minor'] # Define the actual data student_data = ['Jack', 23, 'Physics', 'Chemistry'] # 1. Open a new CSV file with open('students.csv', 'w') as file: # 2. Create a CSV writer writer = csv.writer(file) # 3. Write data to the file writer.writerow(student_header) writer.writerow(student_data)
This will create the students.csv file into the folder you are currently working in. The new file will look like this:
How to write multiple lines to a CSV file in Python
In Python you can use the writerows of the CSV writer () function writes multiple rows to a CSV file simultaneously.
example. Let's say you want to write multiple rows of data to a CSV file. For example, you might have a list of students instead of just one.
To write multiple rows of data to CSV, use the writerows() method.
Here is an example:
import csv student_header = ['name', 'age', 'major', 'minor'] student_data = [ ['Jack', 23, 'Physics', 'Chemistry'], ['Sophie', 22, 'Physics', 'Computer Science'], ['John', 24, 'Mathematics', 'Physics'], ['Jane', 30, 'Chemistry', 'Physics'] ] with open('students.csv', 'w') as file: writer = csv.writer(file) writer.writerow(student_header) # Use writerows() not writerow() writer.writerows(student_data)
This will generate a new CSV file that looks like this:
How to do it in Python Write the dictionary to the CSV file
Using the DictWriter object can write the dictionary to the CSV file in Python, including the following three steps:
1. Use the DictWriter object of the csv module and which specifies the field name.
2. Use the writeheader() method to create a header into a CSV file.
3. Use the writerows() method to write dictionary data to the file.
Example: Let’s write the student data dictionary to a CSV file.
import csv student_header = ['name', 'age', 'major', 'minor'] student_data = [ {'name': 'Jack', 'age': 23, 'major': 'Physics', 'minor': 'Chemistry'}, {'name': 'Sophie', 'age': 22, 'major': 'Physics', 'minor': 'Computer Science'}, {'name': 'John', 'age': 24, 'major': 'Mathematics', 'minor': 'Physics'}, {'name': 'Jane', 'age': 30, 'major': 'Chemistry', 'minor': 'Physics'} ] with open('students.csv', 'w') as file: # Create a CSV dictionary writer and add the student header as field names writer = csv.DictWriter(file, fieldnames=student_header) # Use writerows() not writerow() writer.writeheader() writer.writerows(student_data)
Now the result is the same as the students.csv file in the previous example:
Conclusion
CSV or comma separated values is a Commonly used file formats. It consists of values usually separated by commas.
To write CSV in Python, you need to use the csv module by following these steps:
1. Open the CSV file in write mode.
2. Create a CSV writer object.
3. Write data to CSV file.
4. Close the CSV file.
This is a practical example.
import csv data = ["This", "is", "a", "Test"] with open('example.csv', 'w') as file: writer = csv.writer(file) writer.writerow(data)
Happy coding!
The above is the detailed content of How to read and write csv files in Python. For more information, please follow other related articles on the PHP Chinese website!

The reasons why Python scripts cannot run on Unix systems include: 1) Insufficient permissions, using chmod xyour_script.py to grant execution permissions; 2) Shebang line is incorrect or missing, you should use #!/usr/bin/envpython; 3) The environment variables are not set properly, and you can print os.environ debugging; 4) Using the wrong Python version, you can specify the version on the Shebang line or the command line; 5) Dependency problems, using virtual environment to isolate dependencies; 6) Syntax errors, using python-mpy_compileyour_script.py to detect.

Using Python arrays is more suitable for processing large amounts of numerical data than lists. 1) Arrays save more memory, 2) Arrays are faster to operate by numerical values, 3) Arrays force type consistency, 4) Arrays are compatible with C arrays, but are not as flexible and convenient as lists.

Listsare Better ForeflexibilityandMixdatatatypes, Whilearraysares Superior Sumerical Computation Sand Larged Datasets.1) Unselable List Xibility, MixedDatatypes, andfrequent elementchanges.2) Usarray's sensory -sensical operations, Largedatasets, AndwhenMemoryEfficiency

NumPymanagesmemoryforlargearraysefficientlyusingviews,copies,andmemory-mappedfiles.1)Viewsallowslicingwithoutcopying,directlymodifyingtheoriginalarray.2)Copiescanbecreatedwiththecopy()methodforpreservingdata.3)Memory-mappedfileshandlemassivedatasetsb

ListsinPythondonotrequireimportingamodule,whilearraysfromthearraymoduledoneedanimport.1)Listsarebuilt-in,versatile,andcanholdmixeddatatypes.2)Arraysaremorememory-efficientfornumericdatabutlessflexible,requiringallelementstobeofthesametype.

Pythonlistscanstoreanydatatype,arraymodulearraysstoreonetype,andNumPyarraysarefornumericalcomputations.1)Listsareversatilebutlessmemory-efficient.2)Arraymodulearraysarememory-efficientforhomogeneousdata.3)NumPyarraysareoptimizedforperformanceinscient

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version
Chinese version, very easy to use

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
