CSV (Comma Separated Values) files are a common method for storing tabular data in a text file. Python has a standard library that supports both reading and writing CSV files.
To read a CSV file into a list of tuples, you can use the csv module as follows:
import csv with open('myfile.csv', 'r') as f: reader = csv.reader(f) data = [row for row in reader]
To write a list of tuples to a CSV file, you can use the csv module as follows:
import csv with open('myfile.csv', 'w') as f: writer = csv.writer(f) writer.writerows(data)
Here is an example that shows how to read and write a CSV file:
import csv # Define the CSV data data = [ (1, 'A towel', 1.0), (42, 'it says', 2.0), (1337, 'is about the most', -1), (0, 'massively useful thing', 123), (-2, 'an interstellar hitchhiker can have.', 3) ] # Write the data to a CSV file with open('myfile.csv', 'w') as f: writer = csv.writer(f) writer.writerows(data) # Read the data from the CSV file with open('myfile.csv', 'r') as f: reader = csv.reader(f) data_read = [row for row in reader] # Print the data print(data_read)
Pandas is a popular Python library for data analysis that provides a convenient way to handle CSV files. You can use Pandas to read a CSV file into a DataFrame, which you can then manipulate and save as a CSV file.
import pandas as pd # Read the CSV file into a DataFrame df = pd.read_csv('myfile.csv', index_col=0) # Make some changes to the DataFrame df['Amount'] *= 2 # Write the DataFrame to a new CSV file df.to_csv('new_myfile.csv')
The most common file ending for CSV files is .csv. Other less common endings include .txt and .dat.
Once you have read a CSV file into a list of tuples, a list of dicts, or a Pandas DataFrame, you can work with the data using standard Python methods. For example, you can loop over the data, access individual values, or perform calculations on the data.
In addition to CSV, there are other data formats that you can use in Python. Some common alternatives include:
The above is the detailed content of How to Efficiently Read and Write CSV Files in Python?. For more information, please follow other related articles on the PHP Chinese website!