Python让繁琐工作自动化——chapter14 处理CSV和JSON数据

1. 基础语法

1.1 CSV模块

(1)读取CSV文件

csvobj = open(csvfile)                   #打开CSV文件
readerpbj = csv.reader(csvobj)           #将其转换为reader对象

(2)写入数据

output = open(csvfile, 'w', newline='')  # 创建要写入的CSV文件
csvwriter = csv.writer(output)  # 将其转换为writer对象
csvwriter.writerow(row)  # 用writerow函数写入数据

(3)关键字参数

csvwriter = csv.writer(csvfiel , delimiter = '\t , lineterminator = '\n\n')  
# delimiter参数为分隔符  lineterminator参数为间距

(4)实例应用

删除许多CSV文件的第一行,重新写入一个_removed文件

import  csv,os

#找寻当前路径下所有CSV
for csvfile in os.listdir('.'):
    if not csvfile.endswith('.csv'):
        continue
    print('Remove header from '+csvfile +' ...')

#将除第一行之外的所有行添加到列表中
    csvrow = []
    csvobj = open(csvfile)
    readerpbj = csv.reader(csvobj)
    for row in readerpbj:
        if readerpbj.line_num ==1:
            continue
        csvrow.append(row)
    csvobj.close()

#写入新CSV文件
    output = open('Removed'+csvfile,'w')
    # output = open(os.path.join('RemovedHeader',csvfile),'w',newline='')
    csvwriter = csv.writer(output)
    for row in csvrow:
        csvwriter.writerow(row)
    output.close()


1.2 JSON模块

(1)json.loads()

将包含JSON数据的字符串转换为Python的值

weatherData = json.loads(response.text)

(2)json.dumps()

讲一个Python值转换为JSON格式的字符串

value = {'isCat':True,'name':'Zophie}
Jsondata = json.dumps(value)

(3) 实例应用

在指定网址api获取天气数据并通过json解析数据,拿到天气等相关信息,但是在运行时遇到了如下错误:

requestsHTTPError: 401 Client Error: Unauthorized for url

不知道如何解决,先把示例代码贴上来吧

#书上给的代码是通过脚本执行,在命令行读取指令
#! python3
# quickWeather.py - Prints the current weather for a location from the command line.

import json, requests, sys

# Compute location from command line arguments.
if len(sys.argv) < 2:
    print('Usage: quickWeather.py location')
    sys.exit()
location = ' '.join(sys.argv[1:])
#San Francisco CA
# location = input("请输入要查询的城市及国家代码: ")

# Download the JSON data from OpenWeatherMap.org's API
url ='http://api.openweathermap.org/data/2.5/forecast/daily?q=%s&cnt=3' % (location)
response = requests.get(url)
response.raise_for_status()

# Load JSON data into a Python variable.
weatherData = json.loads(response.text)

# Print weather descriptions.
w = weatherData['list']
print('Current weather in %s:' % (location))
print(w[0]['weather'][0]['main'], '-', w[0]['weather'][0]['description'])
print()
print('Tomorrow:')
print(w[1]['weather'][0]['main'], '-', w[1]['weather'][0]['description'])
print()
print('Day after tomorrow:')
print(w[2]['weather'][0]['main'], '-', w[2]['weather'][0]['description'])

2 课后习题

2.1 EXCEL到CSV的转换程序

    将当前路径下的CSV文件全部输出为CSV文件,一个Excel文件中可能包含多个工作表,必须为每个表创建一个CSV文件,重命名格式为  文件名_表标题.csv

# 2018/3/20  13:27
import csv,openpyxl,os

for file in os.listdir('.'):
    if not file.endswith('.xlsx'):       #不是xlsx文件就接着往下找
        continue
    wb = openpyxl.load_workbook(file)
    sheets = wb.get_sheet_names()        #找到当前文件中所有sheet

    for i in  range(len(sheets)):
        sheet = wb.get_sheet_by_name(sheets[i])         #在sheets列表中依次循环找
        print('正在写入' + sheet.title +'文件')
        csvfilename = open(file.split('.')[0] + sheet.title + '.csv','w')
        csvwriter = csv.writer(csvfilename)

        for rownum in range(1,sheet.max_row+1):                #循环每一个cell的值,将每一行写入rowdata中
            rowdata = []
            for colnum in range(1,sheet.max_column+1):
                rowdata.append(sheet.cell(row = rownum, column = colnum).value)
            csvwriter.writerow(rowdata)                        #将每一行的值写入csv文件中

    csvfilename.close()

你可能感兴趣的:(Python学习,python)