Python 文件读写
1. 可以一次性加载到内存中
def read_file(file_name):
with open(file_name, "r", errors='ignore', encoding='utf-8') as f:
str = f.read()
print(str)
2.按行读取
def read_file_by_line(file_name):
with open(file_name, "r", errors='ignore', encoding='utf-8') as f:
line = f.readline()
while line:
print(line)
line = f.readline()
3.按字节读取
f.read(size)
4.简单示例
下面是一个简单的实例,涉及Python中的IO以及OS模块。日常生活中,免不了拿手机拍照,为了防止手机中的照片意外丢失,良好的习惯是将照片定期备份,当然,简单期间,你可以使用各种云服务,将照片备份到服务器上,当然,个人习惯不同,我本人更习惯将照片备份到本地,并做一些个性化的处理,比如按拍照日期自动归类。
以下是示例方代码:
照片拷贝方法
def photo_copy(source, target):
with open(source, "rb") as s:
if os.path.exists(target):
print("%s exist" % target)
else:
with open(target, "wb") as t:
b = s.read(1024)
while len(b) > 0:
t.write(b)
b = s.read(1024)
注意:这里按字节读取:
read(size)
读取照片,并根据拍照日期,自动归类: yyyy/yyyyMM:
def get_photos(dir_name, target):
files = os.listdir(dir_name)
for f in files:
file_path = os.path.join(dir_name, f)
if os.path.isfile(file_path):
create_time = datetime.fromtimestamp(os.path.getmtime(file_path))
print("%s is file, create time is %s" % (f, create_time))
format_time = create_time.strftime("%Y%m")
year = create_time.strftime("%Y")
target_file = os.path.join(target, year, format_time)
if os.path.exists(target_file):
print("%s exist" % target_file)
else:
print("%s not exist, do make dirs" % target_file)
os.makedirs(target_file)
print("ready to copy %s => %s" % (file_path, os.path.join(target_file, f)))
photo_copy(file_path, os.path.join(target_file, f))
print("file copy finished!")
else:
print("%s is not file" % f)
还没有评论,来说两句吧...