9.Python - 读写文件

本文介绍Python中文件的基本操作,包括如何使用换行符、不同模式打开文件、向文件写入内容、追加内容以及多种读取文件的方法。

\n 换行命令

定义 text 为字符串, 并查看使用 \n 和不适用 \n 的区别:


text='This is my first test. This is the second line. This the third '

print(text)  # 无换行命令


"""

This is my first test. This is the second line. This the third

"""


text='This is my first test.\nThis is the second line.\nThis the third line'

print(text)   # 输入换行命令\n,要注意斜杆的方向。注意换行的格式和c++一样


"""

This is my first test.

This is the second line.

This the third line

"""


open 读文件方式

使用 open 能够打开一个文件, open 的第一个参数为文件名和路径 'my file.txt', 第二个参数为将要以什么方式打开它, 比如 w 为可写方式,r为只读方式,a为追加方式 . 如果计算机没有找到 'my file.txt' 文件, w 方式创建一个新的文件, 并命名为 my file.txt


my_file=open('my file.txt','w')   #用法: open('文件名','形式'), 其中形式有'w':write;'r':read.

my_file.write(text)               #该语句会写入先前定义好的 text

my_file.close()                   #关闭文件



appended给文件增加内容

我们先保存一个已经有3行文字的 my file.txt 文件, 文件的内容如下:

This is my first test. 

This is the second line.

This the third

然后使用添加文字的方式给这个文件添加一行 This is appended file.”, 并将这行文字储存在 append_file 里,注意\n的适用性:


append_text='\nThis is appended file.'  # 为这行文字提前空行 "\n"

my_file=open('my file.txt','a')   # 'a'=append 以增加内容的形式打开

my_file.write(append_text)

my_file.close()


""""

This is my first test.

This is the second line.

This the third line.

This is appended file.

""""

#运行后再去打开文件,会发现会增加一行代码中定义的字符串


读取文件内容 file.read()

使用 file.read() 能够读取到文本的所有内容.


file= open('my file.txt','r') 

content=file.read()  

print(content)


""""

This is my first test.

This is the second line.

This the third line.

This is appended file.    

""""


按行读取 file.readline()

如果想在文本中一行行的读取文本, 可以使用 file.readline(), file.readline() 读取的内容和你使用的次数有关, 使用第二次的时候, 读取到的是文本的第二行, 并可以以此类推:

file= open('my file.txt','r') 

content=file.readline()  # 读取第一行

print(content)


""""

This is my first test.

""""


second_read_time=file.readline()  # 读取第二行

print(second_read_time)


"""

This is the second line.

"""


读取所有行 file.readlines()

如果想要读取所有行, 并可以使用像 for 一样的迭代器迭代这些行结果, 我们可以使用 file.readlines(), 将每一行的结果存储在 list 中, 方便以后迭代.


file= open('my file.txt','r') 

content=file.readlines() # python_list 形式

print(content)


""""

['This is my first test.\n', 'This is the second line.\n', 'This the third line.\n', 'This is appended file.']

""""


# 之后如果使用 for 来迭代输出:

for item in content:

    print(item)

    

"""

This is my first test.


This is the second line.


This the third line.


This is appended file.

"""


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值