python之文件读写

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']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值