换行\n
text='First line.\nSecond line.\nLast line.'
print(text)
输出如下:
First line.
Second line.
Last line.
\t tab对齐
在需要实现tab对齐的行的开头加上\t即可实现。
open
open(‘文件路径’,’打开方式’)
打开方式有以下几种(仅列出常用方式):
- ‘r’:只读,文件指针在文件开头。
- ‘r+’:读写,文件指针在开头。
- ‘w’:只写,如果文件存在则打开文件,并从头开始编辑,原有内容会被删除;若文件不存在,则创建新文件。
- ‘w+’:读写。其余同上。
- ‘a’:追加。若文件存在,则指针在文件结尾;若不存在,创建新文件进行写入。
- ‘a+’:读写,其余同上。
text='First line.\nSecond line.\nLast line.'
my_file=open('test1.txt','w')
my_file.write(text)
my_file.close() #注意一定要关闭才能成功写入
给文件增添内容
使用’a’打开方式来对文件进行追加。
text='\tFirst line.\n\tSecond line.\n\tLast line.'
my_file=open('test1.txt','a')
my_file.write('\nThis is the appended line.')
my_file.close()
修改后的文件内容:
First line.
Second line.
Last line.
This is the appended line.
读取文件内容 file.read()
# 读取文件全部内容
file=open('test1.txt','r')
text=file.read()
print(text)
输出如下:
First line.
Second line.
Last line.
This is the appended line.
按行读取 file.readline()
读取第几次就是第几行
# 按行读取
file=open('test1.txt','r')
text1=file.readline()
print('text1:',text1)
text2=file.readline()
print('text2:',text2)
输出如下:
text1: First line.
text2: Second line.