小白python学习——文件的读入和书写

1.打开文件(这个文件是pycharm中创建的txt)

filename='LOVE.txt'
with open(filename) as file:
    files=file.readlines()
for i in files:
    print(i)
ZY I Love YOU


We have know each other a long time
在with代码块中打开文件,readlines函数是把txt文件中打包成列表

2.直接创建文件和在文件中读入字符串

filename='LOVE.txt'
with open(filename,'w') as file:
    file.write("YOU LOVE ME")
 
 
YOU LOVE ME

'w'是写入的形式,书上很多种,可以去看,运用的函数是write函数

猜你喜欢

转载自blog.csdn.net/qq_40602790/article/details/81066603