# 操作csv格式文件:纯文本格式存储表格数据
# with open(r'D:\Python\路飞\模块2\day09 文件操作相关\安澜府.csv',mode='r',encoding='utf-8') as file_objct:
import os
import requests
with open(r'D:\xxx\xxx\xxx\xxx\xxx.csv',mode='r',encoding='gbk') as file_objct: # 因为这个文件存储的是gbk格式,一般来说用utf-8格式
a = file_objct.readline() # 读取第一行,第一行是标题,不取值,光标到第一行末尾,取值剩下的内容
for line in file_objct: # 遍历所有的内容
user_id,user_name,user_url = line.strip().split(',') # 因为每一行最后有换行符,所以把先去除换行符,再切割
print(user_name,user_url)
# 1.根据URL下载图片,为了下载需要,headers内容不动
res = requests.get(
url=user_url,
headers={
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
}
)
# 2.如果文件夹不存在,则创建新文件夹
if not os.path.exists('image'):
os.mkdir('image')
# 3.写入新的文件
with open(f'image/{user_name}.png',mode='wb') as b:
b.write(res.content)
# 案例:基于csv格式实现,用户的注册 & 登录认证。详细需求如下:
import os
import csv
if not os.path.exists('day09 文件操作相关/user_info.csv'):
os.mkdir('day09 文件操作相关/user_info.csv')
headers = ['序号','用户名','密码']
rows = []
count = 1
while True:
user_infor = []
user_name = input('请输入用户名:')
if user_name == 'Q' or user_name == 'q':
break
user_code = input('请输入密码:')
user_infor.append(count)
user_infor.append(user_name)
user_infor.append(user_code)
rows.append(user_infor)
count += 1
print(rows)
with open('user.csv',mode='w',encoding='gbk') as f:
f_csv = csv.writer(f)
f_csv.writerow(headers)
f_csv.writerows(rows)
with open('user.csv',mode='a',encoding='utf-8') as f:
count = 1
while True:
user_name0 = input('请注册用户名:')
if user_name0 == 'Q' or user_name0 == 'q':
break
user_code0 = input('设置密码:')
f.write(f"{count},{user_name0},{user_code0}\n")
count += 1
f.flush()
while True:
a = input('是否登录?Y/N')
a = a.upper()
if a not in {'Y','N'}:
print('您输入的格式不对,清重新输入!')
continue
elif a == 'N':
break
user_name1 = input('请输入用户名:')
if user_name1 == 'Q' or user_name1 == 'q':
break
user_code1 = input('请输入密码:')
with open('user.csv',mode='r',encoding='utf-8') as g:
for line in g:
count,user,code = line.strip().split(',')
if not (user_name1 == user and user_code1 == code):
print('您输入的用户名或密码不对!请重新输入!')
break
else:
print('登录成功!')
break