您的位置:首页 > 编程语言 > Python开发

基于python的-本地.txt文件的读写

2018-01-24 18:01 411 查看
# 读写txt文本文件

# 1.打开文件
# 使用python内置的open函数 打开txt文件
# 要打开的文件名称
#  mode  模式: w 只能操作写入,r 只能读取, a 向文件追加
#              w+ 可读可写, r+ 可读可写, a+ 可读可追加
#              wb+ 写入进制数据
# r 模式只能打开已存在的文件
# w 模式打开文件,如果文件中有数据,再次写入内容,会把原来的覆盖掉
# a 模式打开文件,如果文件中有数据,再次写入内容,会在后面接着写
# 步骤
# (1)打开文件
file_handle = open('1.txt', mode='w')
# (2)向文件写入数据
#   (2.1)write 写入
# \n 换行符
file_handle.write('hello world\n')
file_handle.write('你好,世界\n')
#   (2.2)writelines()函数,会将列表中的字符串写入文件中,但不会自动换行,
#        如果需要换行,手动添加换行符
#    参数 必须是一个只存放字符串的列表
file_handle.writelines(['hello\n', 'world\n', '你好\n', '郑州\n'])
# (3)关闭文件
file_handle.close()

# 1.打开文件
# 使用r模式打开文件,做读取文件操作
# 打开文件的模式,默认就是r模式,如果只是读文件,可以不填写mode模式
file_handle = open('1.txt',mode='r')

# 2.读取文件内容
# (2.1) read()函数,读取文件内容。如果指定读取长度,会按照长度去读取,不指定
# 则读取所有数据
# content = file_handle.read()
# print(content)
# (2.2)readline(int)函数,默认读取文件中一行数据
# content = file_handle.readline()
# print(content)
# content2 = file_handle.readline()
# print(content2)
# content3 = file_handle.readline()
# print(content3)
# (2.3)readlines() 读取所有行的数据,会把每一行的数据作为一个元素,
#                    放在列表返回
contents = file_handle.readlines()
print(contents)
# 使用for循环,遍历列表中的每一条数据

# 3.关闭文件
file_handle.close()

# tell()函数 返回当前文件中光标的位置
file_handle = open('1.txt')
# 先读取一行数据
content = file_handle.readline()
print(content)
# 获取光标的位置
number = file_handle.tell()
print(number)
# seek()函数,调整光标位置 offset : 偏移量
# seek第一个参数:offect 直接指定文件的光标位置
# seek第二个参数:0 直接移动到开始位置  1 当前位置  2 末尾位置 (默认值0)
file_handle.seek(0, 2)
number = file_handle.tell()
print(number)
content1 = file_handle.readline()
print(content1)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: