Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

csv存入汉字内容乱码 #47

Open
11003 opened this issue Apr 21, 2023 · 2 comments
Open

csv存入汉字内容乱码 #47

11003 opened this issue Apr 21, 2023 · 2 comments

Comments

@11003
Copy link

11003 commented Apr 21, 2023

将数据写入CSV文件

csv存入汉字内容乱码

import csv
import random

with open('scores.csv', 'w',encoding='utf-8') as file:
    writer = csv.writer(file, delimiter='|', quoting=csv.QUOTE_ALL)
    writer.writerow(['姓名', '语文', '数学', '英语'])
    names = ['关羽', '张飞', '赵云', '马超', '黄忠']
    for name in names:
        scores = [random.randrange(50, 101) for _ in range(3)]
        scores.insert(0, name)
        writer.writerow(scores)
@11003
Copy link
Author

11003 commented Apr 21, 2023

从CSV文件读取数据 同理:

with open('scores.csv', 'r',encoding='utf-8') as file:
    reader = csv.reader(file, delimiter='|')
    for data_list in reader:
        print(reader.line_num, end='\t')
        for elem in data_list:
            print(elem, end='\t')
        print()

@11003
Copy link
Author

11003 commented Apr 21, 2023

需要加上encoding='utf-8'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant