1
text='This is my first test.\nThis is the next line.\nThis is the last line.\n' print(text )
运行结果:
2 创建一个文件 并且往文件里写入句子
text='This is my first test.\nThis is the next line.\nThis is the last line.\n' my_file=open('my file.txt','w'); my_file.write(text) my_file.close()
运行结果:
注意:文件打开后一定要调用close()关闭文件 否则会系统紊乱
3 在已有文件中追加字
append_text='\nThis is appended text.\n' my_file=open('my file.txt','a');#append的标码即为a my_file.write(append_text) my_file.close()
运行结果:
4 关于读文件
file=open('my file.txt','r') content=file.read() print(content)
运行结果:
5 关于逐行读出与全部输出
逐行输出:
file=open('my file.txt','r') content=file.readline() content2=file.readline() print(content,content2)
运行结果:
全部一起输出:
file=open('my file.txt','r')
content=file.readlines()
print(content)
运行结果:
D:\PycharmProjects\pythonProject\venv\Scripts\python.exe D:/PycharmProjects/pythonProject/hello.py
['This is my first test.\n', 'This is the next line.\n', 'This is the last line.\n', 'This is appended text.\n', '\n', 'This is appended text.\n']