"Python self-taught" file Chapter IX

Reading and Writing Files

st = open("pythontest.txt","w+")#可读可写模式
st.write("hi from python")
st.close()#一定要关闭


If you keep forgetting to close the file, then try this method

with open("pythontest.txt","w+") as f:
    f.write("yes")#会把之前的内容覆盖掉

Read the file

with open("pythontest.txt","r") as f:#换成r模式
    print(f.read())

CSV module

Write

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"])

read

import csv

with open("st.csv","r") as f:
    r = csv.reader(f,
                   delimiter=",")
    for row in r:
        print(",".join(row))

Exercise Challenge

1. To find a file on your computer, and use the Python print its contents.

with open("data.txt","r") as f:
    print(f.read())

2. Write a program to the user to ask questions, and answer save to a file.

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. The following list of elements to write to a CSV file: [[ "Top Gun", "Risky Business",
"Minority Report"], [ "Titanic", "at The Revenant", "Inception"],
[ "Training Day" , "Man on Fire", " Flight"]]. Each list in the file should each accounted for
one line, where the elements separated by commas.

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"])
Published 42 original articles · won praise 0 · Views 266

Guess you like

Origin blog.csdn.net/qq_43169516/article/details/103936377