读写文件
st = open("pythontest.txt","w+")#可读可写模式
st.write("hi from python")
st.close()#一定要关闭
如果一直忘记关闭文件,那就试一下这个方法
with open("pythontest.txt","w+") as f:
f.write("yes")#会把之前的内容覆盖掉
读取文件
with open("pythontest.txt","r") as f:#换成r模式
print(f.read())
CSV模块
写入
import csv
with open("st.csv","w+",newline = '') as f:
w = csv.writer(f,
delimiter=",")
w.writerow(["one",
"two",
"three"])
w.writerow(["four",
"five",
"six"])
读
import csv
with open("st.csv","r") as f:
r = csv.reader(f,
delimiter=",")
for row in r:
print(",".join(row))
挑战练习
1.在计算机上找一个文件,并使用 Python 打印其内容。
with open("data.txt","r") as f:
print(f.read())
2.编写一个程序来向用户提问,并将回答保存至文件。
a1 = input("第一个问题?")
a2 = input("第二个问题?")
a3 = input("第三个问题?")
a4 = input("第四个问题?")
list1 = [a1,a2,a3,a4]
with open("问答.txt","w+") as file:
for i in list1:
w = file.write(i)
3.将以下列表中的元素写入一个 CSV 文件:[[“Top Gun”, “Risky Business”,
“Minority Report”], [“Titanic”, “The Revenant”, “Inception”],
[“Training Day”, “Man on Fire”, “Flight”]]。每个列表应该在文件中各占
一行,其中元素使用逗号分隔。
import csv
with open ("练习.csv","w",newline="") as file :
w = csv.writer(file,
delimiter = ",")
w.writerow(["Top Gun", "Risky Business", "Minority Report"])
w.writerow(["Titanic", "The Revenant", "Inception"])
w.writerow(["Training Day", "Man on Fire", "Flight"])