python学习笔记06(读写文件)

读文件

Created on Mon Feb 12 00:18:30 2018

@author: myself
"""

f = open("data.txt")   #打开文件
data = f.read()        #文件内容写入字符串data
print(data)            #输出字符串

f.close()              #关闭文件,释放资源
runfile('F:/Python/List31.py', wdir='F:/Python')
HAAAA!
I’m in a file
So cool!

写入文件

data = "I will be in a file.\nSo cool!"
out = open("output.txt","w")
f = out.write(data)
out.close()

游戏一:从一个文件中读出内容,保存至另一个文件。

Created on Mon Feb 12 00:45:32 2018

@author: myself
"""

f = open("List32DataOut.txt")  #打开文件
list = f.read()                #读取文件内容

p = open("List32DataIn.txt","w") #新建文件
p.write(list)                    #写入内容
f.close()
p.close()

q = open("List32DataIn.txt")    #打开新建的文件
print(q.read())                 #打开写入的内容
q.close()

游戏二:从控制台输入一些内容,保存至一个文件。

Created on Mon Feb 12 00:56:19 2018

@author: myself
"""

print("请输入内容:")   
list = input()          #记录控制台输入的内容
 
s = open("List32Test2In.txt","w")  #将list写入新的文件中
s.write(list)
s.close()

p = open("List32Test2In.txt")      #输出新的文件
print(p.read())
p.close()



你可能感兴趣的:(python学习笔记06(读写文件))