首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Python文件读写操作

Python文件读写操作

原创
作者头像
陈不成i
修改2021-06-18 18:08:52
修改2021-06-18 18:08:52
5730
举报
文章被收录于专栏:ops技术分享ops技术分享
  1. #读写文件操作
  2. HelloFile = open('/xxx/a.txt','r') #读文件
  3. HelloFile.read() #读整个
  4. HelloFile.readlines() #每一行放到列表里
  5. name = open('a.txt','w') #a追加
  6. name.write('xxxx') #写入,并返回字节数
  7. print(poem, file=fout) #同上写入文件,但会添加换行和空格
  8. print(poem, file=fout, sep='', end='') #默认是同上,可自定义
  9. name.close()
  10. with open('test.txt') as test_file: #将文件做成变量,可以进行操作
  11.     a = test_file.read() #存储到字符串中
  12. print(a)
  13. for line in test_file: #直接进行逐行读取
  14. with open('test.txt','w') as test_file: #写入模式
  15.     test_file.write("内容") #写入内容,在非交互,会返回写入多少字节
  16. w #写入,文件不存在将创建,存在将清空
  17. r #只读,也是默认
  18. a #追加
  19. r+ #读写
  20. rt #t是文本,b是二进制
  21. print(name,file=test_file) #写入内容
  22. #循环分段写入
  23. size = len(poem)
  24. offset = 0
  25. chunk = 100
  26. while True:
  27. if offset > size:
  28. break
  29.     fout.write(poem[offset:offset+chunk])
  30.     offset += chunk
  31. poem = ''
  32. fin = open('a.txt','r')
  33. chunk = 100
  34. while True:
  35.     fragment = fin.trad(chunk)
  36. #line = fin.readline() #每次读一行
  37. if not fragment:
  38. break
  39.     poem += fragment
  40. fin.close()
  41. for line in fin:
  42.     poem += line
  43. #返回列表
  44. fin = open('relativity', 'rt' )
  45. lines = fin.readlines()
  46. fin.close()
  47. #写入到二进制进行操作
  48. import shelve
  49. shelFile = shelve.open('data') #可保存变量
  50. cats = ['abc','bcd']
  51. shelFile['cats'] = cats
  52. print(shelFile['cats']) #可读可写
  53. print(list(shelFile.keys())) #返回一个列表,只有键
  54. shelFile.close()
  55. name.write('cats = ' + pprint.pformat()cats) #写入变量到文件
  56. import xx
  57. xx.cats #可以直接显示出变量来
  58. a = xx.cats #将变量保存的列表、字典赋值

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档