Python基础——文件的读写

1.\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
"""

2.\t tab 对齐

使用 \t 能够达到 tab 对齐的效果:

text='\tThis is my first test.\n\tThis is the second line.\n\tThis is the third line'
print(text)  #延伸 使用 \t 对齐

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

3.open 读文件方式

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

file = open('file.txt','w')   #用法: open('文件名','形式'), 其中形式有'w':write;'r':read.
file.write(text)               #该语句会写入先前定义好的 text
file.close()                   #关闭文件

将会看到在脚本的同级目录上会创建一个file.txt文件,里面有text的内容
在这里插入图片描述

4.给文件增加内容

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

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

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

append_text = '\nThis is appended file.'     # 为这行文字提前空行 "\n"
file = open('file.txt','a')       # 'a'=append 以增加内容的形式打开
file.write(append_text)
file.close()

将会看到在脚本的同级目录上会有一个file.txt文件,里面有text的内容还有我们刚刚append的内容
在这里插入图片描述

5.读取文件内容

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

file_ = open('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.

6.读取文件的一行

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

file_ = open('file.txt','r')
content = file_.readline()
print(content)

#输出
This is my first test.

7.读取文件的所有行

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

file_ = open('file.txt','r')
content = file_.readlines()
print(content)

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

如果使用 for 来迭代输出:

file_ = open('file.txt','r')
content = file_.readlines()
for item in content:
    print(item)

#输出
This is my first test.

This is the second line.

This the third line

This is appended file.
发布了173 篇原创文章 · 获赞 505 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_37763870/article/details/105091154