Python collects data and saves it as csv. How to solve the problem that the file content is garbled?

If the data collected by your Python program is garbled when saved into a CSV format file, you can try the following solutions:

1. Specify the encoding method when opening the CSV file

You can use the function in Python open()to open a CSV file, and open()specify the file encoding method in the function to be the original encoding method of the CSV file. If the original encoding of the CSV file is UTF-8, you can open()specify the encoding in the function "utf-8-sig". The sample code is as follows:

import csv

with open('output.csv', 'w', newline='', encoding='utf-8-sig') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['列1', '列2'])
    writer.writerow(['a', '1'])
    writer.writerow(['b', '2'])

In this example, we open output.csvthe file, specify the encoding as "utf-8-sig", and use csv.writer()the function to write data to the file.

2. Convert data to Unicode encoding

Converting the data to Unicode encoding before writing it to a CSV file is also a common workaround. You can use the function in Python unicode()to convert string type data into Unicode encoding. The sample code is as follows:

import csv

with open('output.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow([unicode('列1', 'utf-8'), unicode('列2', 'utf-8')])
    writer.writerow([unicode('a', 'utf-8'), unicode('1', 'utf-8')])
    writer.writerow([unicode('b', 'utf-8'), unicode('2', 'utf-8')])

In this example, we unicode()convert string type data to Unicode encoding using the function, and then use csv.writer()the function to write the data to the file.

Guess you like

Origin blog.csdn.net/fei347795790/article/details/131021294