首页 > 编程语言 >python读写文件模板记录

python读写文件模板记录

时间:2022-09-19 17:56:46浏览次数:111  
标签:文件 python 读写 写入 read file txt open 模板

目录

读写模式

要了解文件读写模式,需要了解几种模式的区别,以及对应指针

r : 读取文件,若文件不存在则会报错

w: 写入文件,若文件不存在则会先创建再写入,会覆盖原文件

a : 写入文件,若文件不存在则会先创建再写入,但不会覆盖原文件,而是追加在文件末尾

rb,wb: 分别与r,w类似,但是用于读写二进制文件

r+ : 可读、可写,文件不存在也会报错,写操作时会覆盖

w+ : 可读,可写,文件不存在先创建,会覆盖

a+ : 可读、可写,文件不存在先创建,不会覆盖,追加在末尾

读文件

python常用的读取文件函数有三种read()、readline()、readlines()

read(可选:size) 一次性读全部内容

一次性读取文本中全部的内容,以字符串的形式返回结果
To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode). size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size characters (in text mode) or size bytes (in binary mode) are read and returned. If the end of the file has been reached, f.read() will return an empty string ('').

with open("test.txt", "r") as f:  # 打开文件
    data = f.read()  # 读取文件
    print(data)

readline() 读取一行内容

只读取文本第一行的内容,以字符串的形式返回结果
f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\n', a string containing only a single newline.

with open("test.txt", "r") as f:
    data = f.readline()
    print(data)

readlines() 读取所有内容,返回列表

读取文本所有内容,并且以列表的格式返回结果,一般配合for循环使用
If you want to read all the lines of a file in a list you can also use list(f) or f.readlines().

with open("test.txt", "r") as f:
    data = f.readlines()
    print(data)

readlines会读到换行符,可用如下方法去除

with open("test.txt", "r") as f:
    for line in f.readlines():
        line = line.strip('\n')  #去掉列表中每一个元素的换行符
        print(line)

从file中读取每行 等同于 readlines()的功能

For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code:

with open("test.txt", "r") as f:
    for line in f:
        print(line, end = '')

写文件

python常用的读取文件函数有三种write()、writelines()、flush()

write(str) 将字符串的内容写入文件,返回写入的字符数

file.write(str)的参数是一个字符串,就是你要写入文件的内容
其他类型的对象在编写之前需要转换为字符串(文本模式)或字节对象(二进制模式)

with open("test.txt", "w") as f:
    int num = f.write('This is a test\n')  # num == 15

writelines(sequence)函数

file.writelines(sequence)的参数是序列,比如列表、字符串序列,它会迭代帮你写入文件
使用 writelines() 函数向文件中写入多行数据时,不会自动给各行添加换行符

# 实现复制一个文本文件a.txt -> b.txt
f = open('a.txt', 'r')
n = open('b.txt','w+')
n.writelines(f.readlines())
n.close()
f.close()

f.seek(offset, whence) 改变文件对象的位置,类比于unix接口lseek

f = open('workfile', 'rb+')
f.write(b'0123456789abcdef')

f.seek(5)      # Go to the 6th byte in the file

f.read(1)

f.seek(-3, 2)  # Go to the 3rd byte before the end

f.read(1)

手动调用flush() 一般open后调用close即可把缓冲区的数据写入文件(即磁盘)中

如果向文件写入数据后,不想马上关闭文件,也可以调用文件对象提供的 flush() 函数,它可以实现将缓冲区的数据写入文件中

f = open("a.txt", 'w')
f.write("写入一行新数据")
f.flush()  # 一般open后调用close即可把缓冲区的数据写入文件(即磁盘)中

参考文章

python官方文档
txt、csv、xlsx等文件读写
python读取、写入txt文本内容
Python write()和writelines()
Python文件操作(I/O)

标签:文件,python,读写,写入,read,file,txt,open,模板
From: https://www.cnblogs.com/kongweisi/p/16708231.html

相关文章

  • Python多线程编程——threading模块
    本文参考:https://blog.csdn.net/youngwyj/article/details/124720041https://blog.csdn.net/youngwyj/article/details/124833126目录前言threading模块1.简介2.创建线......
  • python-程序控制-for
    1.for循环的一般形式fortmpVarinIterable:blocktmpVar是临时变量Iterable是可迭代对象第一行是循环条件,当对可迭代对象的迭代遍历结束时,for循......
  • Python: yield from
     importtimedefdubious():print(f"\033[32;40;7m{'dubiousstart'}\033[0m")whileTrue:send_value=yieldifsend_valueisNone:......
  • 力扣92(java&python)-反转链表Ⅱ(中等)
    题目:给你单链表的头指针head和两个整数 left和right,其中 left<=right。请你反转从位置left到位置right的链表节点,返回反转后的链表。示例1:输入:head=......
  • python主文件调用其他文件函数的方法
    关键:from文件名import函数名主文件(main.py)需要和包含子函数的文件(fun_cal_modulus8.py)放到同一路径下fun_cal_modulus8.pyfromnumpyimport*#8水平defc......
  • Python: 取消numpy科学计数法
    Numpy中默认是使用科学计数法来显示数据的,但是这种做法往往不利于我们观测数据,比如坐标数据等。那么如何取消numpy科学计数法呢,请往下看。np.set_printoptions()import......
  • 基于Python的求职招聘管理系统Django企业招聘管理系统(源码调试+讲解+文档)
    ......
  • python GUI编程
    GUI英文全称是GraphicalUserInterface,中文为图形用户接口。tkinter是pythonGUI编程的一个库。主要分为三步,首先建立一个窗口(设置参数),然后在窗口上放置组件(文本框、......
  • python 网络编程
    IP地址联网设备(电脑)每次介入网络,都会按照网络的规则,分配身份证号码,每个IP地址对应一个设备。每次进入网络IP地址未必相同。查看电脑IP地址windows:ipconfigIP地址就是I......
  • Python: __slots__
     __slots__定义为类属性,约束实例属性,类定义__slots__后,实例就没有__dict__ 子类和父类都定义__slots__后,子类可有全部__slots__属性  父类存在__slots......