文件处理
- 文件读取
f=open("test.txt","r") #"rb"以二进制模式读
g=f.read()
print(g)
f.close()
#文件读取,一定要关闭
readline(),遇到\n or \r为止
2. 文件写
f=open("test_write.txt","w")
f.write('123456')
f.write('\n')
f.write('234567')
f.close()
#文件写操作,是否已创建都行
3. 文件操作
weather_data=[]
f=open("la_weather.csv","r")
data=f.read()
rows=data.split('\n')
print(rows)
for row in rows:
split_row=row.split(",")
weather_data.append(split_row)
print(weather_data)
#[‘1,sunny’,’2,sunny’,’3,sunny’,’4,sunny’,’5,sunny’,’6,rain’,’7,sunny’,’8,sunny’,’9,fog’,’10,rain’]
#[[‘1,sunny’],[‘2,sunny’],[‘3,sunny’],[‘4,sunny’],[‘5,sunny’],[‘6,rain’],[‘7,sunny’],[‘8,sunny’],[‘9,fog’],[‘10,rain’]]
weather=[]
for row in weather_data:
weather.append(row[1])
print(weather)
f.close()
#[‘sunny’,’sunny’,’sunny’,’sunny’,’sunny’,’rain’,’sunny’,’sunny’,’fog’,’rain’]