首页 技术 正文
技术 2022年11月14日
0 收藏 341 点赞 3,107 浏览 1177 个字

1. 读取文本文件代码:

  1. f = open(‘test.txt’, ‘r’)
  2. print f.read()
  3. f.seek(0)
  4. print f.read(14)
  5. f.seek(0)
  6. print f.readline()
  7. print f.readline()
  8. f.seek(0)
  9. print f.readlines()
  10. f.seek(0)
  11. for line in f:
  12. print line,
  13. f.close()

 运行结果:root@he-desktop:~/python/example# python read_txt.py 第一行第二行第三行 第一行第第一行 第二行 [‘\xe7\xac\xac\xe4\xb8\x80\xe8\xa1\x8c\n’, ‘\xe7\xac\xac\xe4\xba\x8c\xe8\xa1\x8c\n’, ‘\xe7\xac\xac\xe4\xb8\x89\xe8\xa1\x8c\n’]第一行第二行第三行 open的第二个参数:

  • r,读取模式
  • w,写入模式
  • a,追加模式
  • r+,读写模式

read()表示读取到文件尾,size表示读取大小。seek(0)表示跳到文件开始位置。readline()逐行读取文本文件。readlines()读取所有行到列表中,通过for循环可以读出数据。close()关闭文件。 2. 写入文本文件代码:

  1. f = open(‘test.txt’, ‘r+’)
  2. f.truncate()
  3. f.write(‘0123456789abcd’)
  4. f.seek(3)
  5. print f.read(1)
  6. print f.read(2)
  7. print f.tell()
  8. f.seek(3, 1)
  9. print f.read(1)
  10. f.seek(-3, 2)
  11. print f.read(1)
  12. f.close()

 运行结果:root@he-desktop:~/python/example# python write_txt.py 34569b truncate()表示清空文件write()写入文本seek(3)定位到第4个元素前,0表示文件开始,也就是第1个元素前。seek(3, 1)第二个参数默认是0,表示从文件开始处读取;1表示从当前位置开始计数;2表示从文件最后开始。read(1)读取一个字节,指针会根据读取的大小移动相应的位置。tell()取得当前指针的位置。 3. 读取文件信息

  1. # coding: utf-8
  2. f = open(‘test.txt’)
  3. print ‘文件名:’, f.name
  4. print ‘是否处于关闭状态:’, f.closed
  5. print ‘打开的模式:’, f.mode

 运行结果:root@he-desktop:~/python/example# python read_info.py 文件名: test.txt是否处于关闭状态: False打开的模式: r  

上一篇: sass学习总结
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,497
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,910
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,744
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,497
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,135
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,298