Python3-笔记-E-011-库-CSV

import csv, pprint

def ReadFile2List():
file = open('example.csv')
reader = csv.reader(file)
data = list(reader)
pprint.pprint(data)
print(data[0][2]) # 可以用下标
print(data[6][1])
'''
[['4/5/2015 13:34', 'Apples', '73'],
['4/5/2015 3:41', 'Cherries', '85'],
['4/6/2015 12:46', 'Pears', '14'],
['4/8/2015 8:59', 'Oranges', '52'],
['4/10/2015 2:07', 'Apples', '152'],
['4/10/2015 18:10', 'Bananas', '23'],
['4/10/2015 2:40', 'Strawberries', '98']]
73
Strawberries
'''

# Reader 对象只能循环遍历一次。要再次读取 CSV 文件,必须调用csv.reader,创建一个对象。
def ReadFileIter():
reader = csv.reader(open('example.csv'))
for row in reader:
print('row #' + str(reader.line_num) + ' ' + str(row))
print(row[1]) # row是个list可以用下标
'''
row #1 ['4/5/2015 13:34', 'Apples', '73']
Apples
row #2 ['4/5/2015 3:41', 'Cherries', '85']
Cherries
row #3 ['4/6/2015 12:46', 'Pears', '14']
Pears
row #4 ['4/8/2015 8:59', 'Oranges', '52']
Oranges
row #5 ['4/10/2015 2:07', 'Apples', '152']
Apples
row #6 ['4/10/2015 18:10', 'Bananas', '23']
Bananas
row #7 ['4/10/2015 2:40', 'Strawberries', '98']
Strawberries
'''


# 按行写入
def Write2CSV():
file = open('output.csv', 'w', newline='')
writer = csv.writer(file)
print('写入了字符和数:%d' % writer.writerow(['4/5/2015 13:34', 'Apples']))
writer.writerow(['4/10/2015 2:40', 'Strawberries', '98'])
writer.writerow(['4/6/2015 12:46'])
file.close()
'''
4/5/2015 13:34,Apples
4/10/2015 2:40,Strawberries,98
4/6/2015 12:46

'''
# 改变分隔符与换行符
def Write2CSV2():
csvFile = open('example.tsv', 'w', newline='')
# 分割使用制表符,换行为两行
csvWriter = csv.writer(csvFile, delimiter='\t', lineterminator='\n\n')
csvWriter.writerow(['apples', 'oranges', 'grapes'])
csvWriter.writerow(['eggs', 'bacon', 'ham'])
csvWriter.writerow(['spam', 'spam', 'spam', 'spam', 'spam', 'spam'])
csvFile.close()
'''
apples oranges grapes

eggs bacon ham

spam spam spam spam spam spam

'''


# 遍历当前目录内的csv去除第一行,然后在此写入到子目录的同名文件中
import csv, os
dirname = 'headerRemoved'
os.makedirs(dirname, exist_ok=True)
for file in os.listdir('.'):
if file.endswith('.csv'):
print('remove header from ' + file + '......')
srcfile = open(file)
reader = csv.reader(srcfile)
data = list(reader)
srcfile.close()

dstfile = open(os.path.join(dirname, file), 'w', newline='')
writer = csv.writer(dstfile)
dstdata = data[1:]
for line in dstdata:
writer.writerow(line)
dstfile.close()


 
posted @ 2017-11-10 10:52  魏桐  阅读(258)  评论(0编辑  收藏  举报