![]() |
|
[Tut] The Ultimate Guide on Converting a CSV in Python - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] The Ultimate Guide on Converting a CSV in Python (/thread-99741.html) |
[Tut] The Ultimate Guide on Converting a CSV in Python - xSicKxBot - 07-25-2022 The Ultimate Guide on Converting a CSV in Python 4/5 – (1 vote) Abstract: In this article, we’ll quickly overview the best method, respectively, to convert a CSV file to JSON, Excel, dictionary, Parquet, list, list of lists, list of tuples, text file, DataFrame, XML, NumPy array, and list of dictionaries.In this article, you’ve learned the best ways to perform the following conversions (click to read more):
How to Convert CSV to JSON in Python? You can convert a CSV file to a JSON file by using the following five steps:
Code: import csv
import json csv_file = 'my_file.csv'
json_file = 'my_file.json' my_json = {}
with open(csv_file, 'r') as fobj: reader = csv.DictReader(fobj) for row in reader: # Use one of the CSV column names as a key key = row['Name'] my_json[key] = row with open(json_file,'w') as fobj: fobj.write(json.dumps(my_json, indent=2))Input CSV File: Code: Name,Job,Age,Income
Alice,Programmer,23,110000
Bob,Executive,34,90000
Carl,Sales,45,50000Output JSON File: Code: { "Alice": { "Name": "Alice", "Job": "Programmer", "Age": "23", "Income": "110000" }, "Bob": { "Name": "Bob", "Job": "Executive", "Age": "34", "Income": "90000" }, "Carl": { "Name": "Carl", "Job": "Sales", "Age": "45", "Income": "50000" }
}There are many more details to it, so if this didn’t answer your question yet, go here: Learn More: Feel free to learn more about this conversion goal in our full guide on the Finxter blog with multiple CSV conversion methods and step-by-step explanations.How to Convert CSV to Excel (XLSX) in Python? ![]() The most pythonic way to convert a Code: .csvCode: .xlsx
Code: import pandas as pd df = pd.read_csv('my_file.csv')
df.to_excel('my_file.xlsx', index=None, header=True)Note that there are many ways to customize the Code: to_excel()
Learn More: Feel free to learn more about this conversion goal in our full guide on the Finxter blog with multiple CSV conversion methods and step-by-step explanations.How to Convert a CSV to a Dictionary in Python? ![]() The best way to convert a CSV file to a Python dictionary is to create a CSV file object Code: fCode: open("my_file.csv")Code: csv.DictReader(f)Code: import csv csv_filename = 'my_file.csv' with open(csv_filename) as f: reader = csv.DictReader(f) for row in reader: print(row) Learn More: Feel free to learn more about this conversion goal in our full guide on the Finxter blog with multiple CSV conversion methods and step-by-step explanations.How to Convert a CSV to a Parquet Format in Python? Here’s a step-by-step approach to reading a CSV and converting its contents to a Parquet file using the Pandas library:
The code snippet to convert a CSV file to a Parquet file is quite simple (steps 4-6): Code: import pandas as pd
df = pd.read_csv('my_file.csv')
df.to_parquet('my_file.parquet') Learn More: Feel free to learn more about this conversion goal in our full guide on the Finxter blog with multiple CSV conversion methods and step-by-step explanations.How to Convert a CSV to a List in Python? ![]() Here’s the code to convert that CSV file to a list of dictionaries, one dictionary per row by using the Code: csv.DictReader(file)Code: import csv csv_filename = 'my_file.csv' with open(csv_filename) as f: reader = csv.DictReader(f) lst = list(*reader) Learn More: Feel free to learn more about this conversion goal in our full guide on the Finxter blog with multiple CSV conversion methods and step-by-step explanations.How to Convert a CSV to a List of Lists in Python? ![]() To convert a CSV file Code: 'my_file.csv'Code: csv.reader(file_obj)Code: list()Code: import csv csv_filename = 'my_file.csv' with open(csv_filename) as f: reader = csv.reader(f) lst = list(reader)Output: Code: print(lst)
# [['9', '8', '7'], ['6', '5', '4'], ['3', '2', '1']] Learn More: Feel free to learn more about this conversion goal in our full guide on the Finxter blog with multiple CSV conversion methods and step-by-step explanations.How to Convert a CSV to a List of Tuples in Python? ![]() To convert a CSV file Code: 'my_file.csv'Code: csv.reader(file_obj)Code: list(tuple(line) for line in reader)Here’s a simple example that converts our CSV file to a list of tuples using this approach: Code: import csv csv_filename = 'my_file.csv' with open(csv_filename) as f: reader = csv.reader(f) lst = list(tuple(line) for line in reader)Output: Code: print(lst)
# [('9', '8', '7'), ('6', '5', '4'), ('3', '2', '1')] Learn More: Feel free to learn more about this conversion goal in our full guide on the Finxter blog with multiple CSV conversion methods and step-by-step explanations.How to Convert a CSV to a Text File in Python? If you want to keep the content (including the delimiter Code: ','Code: .csvCode: .txtCode: open()Code: read()Code: write()In other words, perform the three steps to write a CSV to a TXT file unmodified:
Here’s the code snippet that solves our basic challenge: Code: # 1. Open the CSV file in reading mode and the TXT file in writing mode
with open('my_file.csv', 'r') as f_in, open('my_file.txt', 'w') as f_out: # 2. Read the CSV file and store in variable content = f_in.read() # 3. Write the content into the TXT file f_out.write(content) Learn More: Feel free to learn more about this conversion goal in our full guide on the Finxter blog with multiple CSV conversion methods and step-by-step explanations.How to Convert a CSV to a Pandas DataFrame in Python? To import a given CSV file into a newly-created Pandas DataFrame, use the Code: pd.read_csv('my_file.csv')Code: 'my_file.csv'Here’s a quick and generic code snippet showcasing this approach: Code: import pandas as pd
df = pd.read_csv('my_file.csv')
print(df)Output: Code: Name Job Age Income
0 Alice Programmer 23 110000
1 Bob Executive 34 90000
2 Carl Sales 45 50000 Learn More: Feel free to learn more about this conversion goal in our full guide on the Finxter blog with multiple CSV conversion methods and step-by-step explanations.How to Convert a CSV to an XML in Python? ![]() You can convert a CSV to an XML using the following approach:
Here’s the code: Code: # Convert CSV file to XML string
import csv filename = 'my_file.csv' def convert_row(headers, row): s = f'<row id="{row[0]}">\n' for header, item in zip(headers, row): s += f' <{header}>' + f'{item}' + f'</{header}>\n' return s + '</row>' with open(filename, 'r') as f: r = csv.reader(f) headers = next(r) xml = '<data>\n' for row in r: xml += convert_row(headers, row) + '\n' xml += '</data>' print(xml) Learn More: Feel free to learn more about this conversion goal in our full guide on the Finxter blog with multiple CSV conversion methods and step-by-step explanations.How to Convert a CSV to a NumPy Array in Python? ![]() You can convert a CSV file to a NumPy array simply by calling Code: np.loadtxt()Code: filenameCode: delimiterCode: np.loadtxt('my_file.csv', delimiter=',')Code: 'my_file.csv'Code: ','Here’s an example: Code: import numpy as np array = np.loadtxt('my_file.csv', delimiter=',')
print(array)Output: Code: [[9. 8. 7.] [6. 5. 4.] [3. 2. 1.]] Learn More: Feel free to learn more about this conversion goal in our full guide on the Finxter blog with multiple CSV conversion methods and step-by-step explanations.How to Convert a CSV to a List of Dictionaries? ![]() Convert a CSV file to a list of Python dictionaries in three steps:
Here’s the code to convert that CSV file to a list of dictionaries, one dictionary per row by using the Code: csv.DictReader(file)Code: import csv csv_filename = 'my_file.csv' with open(csv_filename) as f: reader = csv.DictReader(f) lst = list(*reader) Learn More: Feel free to learn more about this conversion goal in our full guide on the Finxter blog with multiple CSV conversion methods and step-by-step explanations.Summary You can find a more detailed article on each topic in the following table: Goal Conversion | Full Article Python CSV to JSON | https://blog.finxter.com/convert-csv-to-json-in-python/ Python CSV to Excel ( Code: .xlsxhttps://blog.finxter.com/convert-csv-to-excel-xlsx-in-python/ Python CSV to Dictionary | https://blog.finxter.com/convert-csv-to-dictionary-in-python/ Python CSV to Parquet | https://blog.finxter.com/python-convert-csv-to-parquet/ Python CSV to List | https://blog.finxter.com/python-convert-csv-to-list/ Python CSV to List of Lists | https://blog.finxter.com/python-convert-csv-to-list-of-lists/ Python CSV to List of Tuples | https://blog.finxter.com/convert-csv-to-list-of-tuples-in-python/ Python CSV to Text File ( Code: .txthttps://blog.finxter.com/python-convert-csv-to-text-file-csv-to-txt/ Python CSV to DataFrame (Pandas) | https://blog.finxter.com/read-a-csv-file-to-a-pandas-dataframe/ Python CSV to XML File ( Code: .xmlhttps://blog.finxter.com/csv-to-xml-how-to-convert-in-python/ Python CSV to NumPy Array ( Code: ndarrayhttps://blog.finxter.com/how-to-convert-a-csv-to-numpy-array-in-python/ Python CSV to List of Dictionaries | https://blog.finxter.com/python-convert-csv-to-list-of-dictionaries/ Feel free to check out the Finxter email academy to keep improving your coding skills. We have cheat sheets! Programmer Humor [i]It’s hard to train deep learning algorithms when most of the positive feedback they get is sarcastic. — from xkcd[/i]
|