Python 文件读写

た 入场券 2022-06-03 09:52 395阅读 0赞

1. 可以一次性加载到内存中

  1. def read_file(file_name):
  2. with open(file_name, "r", errors='ignore', encoding='utf-8') as f:
  3. str = f.read()
  4. print(str)

2.按行读取

  1. def read_file_by_line(file_name):
  2. with open(file_name, "r", errors='ignore', encoding='utf-8') as f:
  3. line = f.readline()
  4. while line:
  5. print(line)
  6. line = f.readline()

3.按字节读取

  1. f.read(size)

4.简单示例

下面是一个简单的实例,涉及Python中的IO以及OS模块。日常生活中,免不了拿手机拍照,为了防止手机中的照片意外丢失,良好的习惯是将照片定期备份,当然,简单期间,你可以使用各种云服务,将照片备份到服务器上,当然,个人习惯不同,我本人更习惯将照片备份到本地,并做一些个性化的处理,比如按拍照日期自动归类。

以下是示例方代码:

照片拷贝方法

  1. def photo_copy(source, target):
  2. with open(source, "rb") as s:
  3. if os.path.exists(target):
  4. print("%s exist" % target)
  5. else:
  6. with open(target, "wb") as t:
  7. b = s.read(1024)
  8. while len(b) > 0:
  9. t.write(b)
  10. b = s.read(1024)

注意:这里按字节读取:

read(size)

读取照片,并根据拍照日期,自动归类: yyyy/yyyyMM

  1. def get_photos(dir_name, target):
  2. files = os.listdir(dir_name)
  3. for f in files:
  4. file_path = os.path.join(dir_name, f)
  5. if os.path.isfile(file_path):
  6. create_time = datetime.fromtimestamp(os.path.getmtime(file_path))
  7. print("%s is file, create time is %s" % (f, create_time))
  8. format_time = create_time.strftime("%Y%m")
  9. year = create_time.strftime("%Y")
  10. target_file = os.path.join(target, year, format_time)
  11. if os.path.exists(target_file):
  12. print("%s exist" % target_file)
  13. else:
  14. print("%s not exist, do make dirs" % target_file)
  15. os.makedirs(target_file)
  16. print("ready to copy %s => %s" % (file_path, os.path.join(target_file, f)))
  17. photo_copy(file_path, os.path.join(target_file, f))
  18. print("file copy finished!")
  19. else:
  20. print("%s is not file" % f)

发表评论

表情:
评论列表 (有 0 条评论,395人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Python 文件

    常用的读写模式的类型有: w 以覆盖的方式打开 a 以追加的方式打开 r+ 以读写模式打开 W+ 以读写模式打开 a+ 以读写模式打开 rb 以二进制读写模

    相关 Python文件

    Python读写文件 1.open 使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。 fi