美文网首页
Python文件操作

Python文件操作

作者: 黄褐色猫头鹰 | 来源:发表于2018-11-08 11:52 被阅读0次
#Python文件操作
#   open(), 用于打开一个文件, 并返回一个文件对象
file1 = open('name.txt', mode='w', buffering=-1, encoding='UTF-8',
             errors=None, newline=None, closefd=True, opener=None)
file1.write('诸葛亮')
file1.close()

file2 = open('name.txt', encoding='UTF-8')
print(file2.read()) #诸葛亮
file2.close()

file3 = open('name.txt', mode='a', encoding='UTF-8')   #a->append, r->read, w->write
file3.write('\n刘备')
file3.close()

#   read([size]) 读取指定字节数
file4 = open('name.txt', encoding='UTF-8')
print(file4.read()) #诸葛亮\n刘备
file4.close()

#   readline([size])读单行, 包括\n字符
file5 = open('name.txt', encoding='UTF-8')
print(file5.readline()) #诸葛亮
file5.close()

#   readlines()读行, 返回可迭代对象
file6 = open('name.txt', encoding='UTF-8')
for line in file6.readlines():
    print(line, end='|')    #诸葛亮\n|刘备| (换行符也会被单独迭代出来一次, 比较奇怪)
file6.close()

#   tell()显示读取文件指针的位置
file7 = open('name.txt', encoding='UTF-8')
print(file7.tell()) #0
print(file7.read(1)) #诸葛亮 read([size]) 读取指定字节数, 这一个参数为1个字节, 但是汉字是三个字节
print(file7.tell()) #3, 因为一个汉字三个字节
file7.close()

#   seek(offset[, whence]) 移动文件读取指针到指定位置
#   offset是偏移量, whence是起始位置设置(默认0开头,1当前位置, 2末尾)
file8 = open('name.txt', encoding='UTF-8')
print('当前文件的位置:', file8.tell()) #当前文件的位置: 0
print('打印输出:', file8.read(1)) #打印输出: 诸
print('当前文件的位置:', file8.tell()) #当前文件的位置: 3
file8.seek(0)
print('seek(0)后的文件的位置:', file8.tell()) #seek(0)后的文件的位置: 0
file8.read(1)
file8.read(1)
print('两次read(1)后的文件的位置:', file8.tell()) #两次read(1)后的文件的位置: 6
file8.close()


相关文章

  • 14.Python之文件操作

    Python之文件操作 文件操作通过Python中的内置函数open()对文件进行操作。文件操作需要如下几个参数:...

  • 第二节课:Python 操作文件 ——软件测试派

    学习目标:掌握 python 操作文件 python 提供内置函数 open()实现对文件的操作。 python ...

  • Python遍历目录并操作文件

    今天来使用python操作文件,包括根据模式查找文件、删除文件操作。 完整代码托管在python/find...

  • 解析Python中的文件操作

    1.简介 在Python中无需引入额外的模块来进行文件操作,Python拥有内置的文件操作函数(除了内置文件操作函...

  • Python 文件操作

    一. Python 读写 创建文件 Python中对文件,文件夹(文件操作函数)的操作需要涉及到OS 模块和 sh...

  • Python

    Python 创建文件 Python 对数据库进行操作--增删改查 Python 对csv进行操作 Python ...

  • python常用文件操作总结

    python 移动文件或文件夹操作。python中对文件、文件夹操作时经常用到的os模块和shutil模块常用方法...

  • python--文件的基本操作

    python编程中,文件是必不可少的。下面我们来学习python中文件的基本操作。 文件的基本操作: 在pytho...

  • Python常用语法二

    Python 字符串操作和文件操作以及其它Python能力补充 Python字符串操作 in和not in: 'x...

  • 文件操作

    Python基础教程 文件内容操作 python中的文件操作还是挺简单的,类似于php中的文件方法,精简好用。我们...

网友评论

      本文标题:Python文件操作

      本文链接:https://www.haomeiwen.com/subject/cezixqtx.html