如果需要数据,评论区留下邮箱!
Python IO与档案处理
f = open('tmp.txt','w')
f.write('hello world')
f.close()
使用with语句省去close()操作
with open('tmp.txt','w') as f:
f.write('hello\nworld')
with open('tmp.txt','r') as f:
print(f.read())
hello
world
将文本一行一行的输出,Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
with open('tmp.txt','r') as f:
for line in f.readlines():
print(line.strip())
hello
world
处理CSV,Excel格式数据
数据来源:国家数据近五年人口数
with open('data\population.csv','r')as f:
for line in f.readlines():
print(line)
指标,2017年,2016年,2015年,2014年,2013年
年末总人口(万人),139008,138271,137462,136782,136072
男性人口(万人),71137,70815,70414,70079,69728
女性人口(万人),67871,67456,67048,66703,66344
城镇人口(万人),81347,79298,77116,74916,73111
乡村人口(万人),57661,58973,60346,61866,62961
使用pandas库的dataframe结构能更好的操作这些数据
import pandas as pd
df = pd.read_csv('data\population.csv',encoding='ANSI')
df
指标 | 2017年 | 2016年 | 2015年 | 2014年 | 2013年 | |
---|---|---|---|---|---|---|
0 | 年末总人口(万人) | 139008 | 138271 | 137462 | 136782 | 136072 |
1 | 男性人口(万人) | 71137 |