CSV:python

  

s="""\
1,tom,20,
2,jerry,30,
3,,,
"""
with open('c:/vbn.csv',mode='wt+') as f:
    # for line in s.splitlines(keepends=True):
    #     print(line)
    #     f.write(line)
    # f.writelines(s.splitlines(keepends=True))

    for line in s.splitlines():
        f.write(line+'\n')

csv_body="""\
id,name,age,comment
1,zs,18,"I'm vbn"
2,ls,20,"this is a ""test"" string"
3,ww,22,"发士大夫"
"""
from pathlib import Path
import csv

path='c:/b/p/vbn.csv'
p=Path(path)
if not p.parent.exists():
    p.parent.mkdir(parents=True)

line1=['1','tom',20,'']
line2=('1','jerry',30)
line3=[line1,line2]

with open(str(p),mode='w') as f:
    writer=csv.writer(f)
    writer.writerow(line1)
    writer.writerow(line2)
    writer.writerows(line3)

with open(str(p),mode='rt+') as f:
    reader=csv.reader(f)
    for line in reader:
        if line:
            print(line,type(line))

p=Path('c:/b/p/vbn.csv')
with open(str(p),mode='rt+') as f:
    reader=csv.reader(f)
    print(next(reader))

row=[4,'vbn',22,'bnm']
rows=[
    (5,'cvb',22,'ui\to'),
    (7,'xcv',77,'')
]

with open(str(p),mode='a+') as f:
    writer=csv.writer(f)
    writer.writerow(row)
    writer.writerows(rows)

 

posted @ 2020-09-19 20:51  ascertain  阅读(90)  评论(0编辑  收藏  举报