14.1.4 delimiter 和 lineterminator 关键字参数
最好不要用delimiter=‘\t’,来进行隔纵行操作,因为没用,
import csv
outputFile = open('output.csv', 'w',newline='')
outputWriter = csv.writer(outputFile,delimiter='\t',lineterminator='\n')
outputWriter.writerow(['apples', 'oranges', 'grapes'])
outputWriter.writerow(['eggs', 'bacon', 'ham'])
outputWriter.writerow(['spam', 'spam', 'spam', 'spam', 'spam', 'spam'])
outputFile.close()
import csv
outputFile = open('output.csv', 'w',newline='')
outputWriter = csv.writer(outputFile,lineterminator='\n')
outputWriter.writerow(['apples', 'oranges', 'grapes'])
outputWriter.writerow(['eggs', 'bacon', 'ham'])
outputWriter.writerow(['spam', 'spam', 'spam', 'spam', 'spam', 'spam'])
outputFile.close()
14.2 项目:从 CSV 文件中删除表头
import csv, os
#os.makedirs()调用将创建 headerRemoved 文件夹,所有的无表头的 CSV 文件将
#写入该文件夹。
os.makedirs('headerRemoved', exist_ok=True)
#在当前工作目录下,循环遍历每一个文件
for csvFilename in os.listdir('.'):
#跳过扩展名不是.csv 的文件
if not csvFilename.endswith('.csv'):
continue
#为了让程序运行时有一些输出,打印出一条消息说明程序在处理哪个 CSV 文件。
print('Removing header from ' + csvFilename + '...')
csvRows = []
csvFileObj = open(csvFilename)
readerObj = csv.reader(csvFileObj)
for row in readerObj:
#Reader 对象的 line_num 属性可以用来确定当前读入的是 CSV 文件的哪一行。
if readerObj.line_num == 1:
continue #跳过第一行
csvRows.append(row)#csvRows 包含了除第一行的所有行
csvFileObj = open(os.path.join('headerRemoved', csvFilename), 'w',
newline='')#打开文件(确定文件地址)
csvWriter = csv.writer(csvFileObj)
for row in csvRows:
csvWriter.writerow(row)
csvFileObj.close()
类似程序的想法:
1,从 CSV 文件读取数据,作为 Python 程序的输入:
import csv
exampleFile = open('example.csv')
exampleReader = csv.reader(exampleFile)
exampleData = list(exampleReader)
print(exampleData[0][0]+', '+exampleData[0][1]+', '+exampleData[0][2])
print(exampleData[1][0]+', '+exampleData[1][1]+', '+exampleData[1][2])
print(exampleData[2][0]+', '+exampleData[2][1]+', '+exampleData[2][2])
2,检查 CSV 文件中无效的数据或格式错误,并向用户提醒这些错误
#向Excel录入正确格式的年月日,时间
import csv
exampleFile = open('example.csv')
exampleReader = csv.reader(exampleFile)
exampleData = list(exampleReader)
for exampledata in exampleData:
#分隔年月日,返回分割后的字符串列表
data=exampledata[0].split('/')
#强制转换一下
if int(data[0])>12 or int(data[0])<=0:
print("此数据不能录入")
else:
print(exampledata[0]+', '+exampledata[1]+', '+exampledata[2])
3,从 CSV 文件拷贝特定的数据到 Excel 文件,或反过来
#向output.csv中录入正确格式的年月日,和日期大于等于6的年月日
import csv
exampleFile = open('example.csv')
exampleReader = csv.reader(exampleFile)
exampleData = list(exampleReader)
outputFile = open('output.csv', 'w', newline='')
outputWriter = csv.writer(outputFile)
for exampledata in exampleData:
data=exampledata[0].split('/')
if int(data[0])>12 or int(data[0])<=0 or int(data[1])<6:
print("此数据不能录入")
else:
outputWriter.writerow(exampledata)
example.csv中内容:
output.csv:
4,在一个 CSV 文件的不同行,或多个 CSV 文件之间比较数据。
略~~
14.4.2 用 dumps 函数写出 JSON
json.dumps()函数(它表示“dump string”,而不是 “dumps”)将一个 Python 值转换成 JSON 格式的数据字符串。
该值只能是以下基本 Python 数据类型之一:字典、列表、整型、浮点型、字符串、布尔型或 None。
14.5 项目:取得当前的天气数据
一直产生这个错误:requests.exceptions.HTTPError:
14.8 实践项目 Excel 到 CSV 的转换程序
import csv,openpyxl,os
for excelFile in os.listdir('.'):
# Skip non-xlsx files, load the workbook object.
if not excelFile.endswith('.xlsx'):
continue
print('Converting file: '+excelFile + '...')
wb=openpyxl.load_workbook(excelFile)
# for sheetName in wb.get_sheet_names():
for sheetName in wb.sheetnames:
# Loop through every sheet in the workbook.
sheet = wb[sheetName]
# Create the CSV filename from the Excel filename and sheet title.
csvFile=open(excelFile[:-5]+'_'+sheetName+'.csv','w',newline='')
# Create the csv.writer object for this CSV file.
csvwriter=csv.writer(csvFile)
# Loop through every row in the sheet.
for rowNum in range(1, sheet.max_row + 1):
rowData = [] # append each cell to this list
# Loop through each cell in the row.
for colNum in range(1, sheet.max_row + 1):
# Append each cell's data to rowData.
rowData.append(sheet.cell(row=rowNum,column=colNum).value)
# Write the rowData list to the CSV file.
csvwriter.writerow(rowData)
csvFile.close()
print("Done!")
用到了 第12章 处理Excel电子表格 的内容