Python中文件的读写

一、换行

text = 'this is my text.thin is zhe second'#定义一个字符串
print(text)

text = 'this is my text.\nthis is zhe second line'#改变该字符串
print (text)

输出:

this is my text.thin is zhe second
this is my text.
this is zhe second line

二、打开一个文件,并且写入东西


text = 'this is my text.\nthis is zhe second line'
print (text)

my_file = open('my file.txt','w')#打开文件,用w的形式可以在该文件里面写东西
my_file.write(text)#把text写到该文件里面去
my_file.close()#关闭文件



以上代码打开了一个txt文件,Python可以在该文件里写东西,我这边没有先生成一个txt文件,运行代码后会在我的工作空间

里生成一个txt文件,文件的内容为text里的内容。

三,

猜你喜欢

转载自blog.csdn.net/weixin_40849273/article/details/82802293