10 python 文件

######## 文件 ########
filename = 'D:/python-web/pythontxt/aaa.txt'
with open(filename,'r') as fileobject:
    fileaa = fileobject.read()
    print(fileaa) #全部读出

    for line in fileaa: #逐行读出
        print(line.rstrip())

#也可以在输出过程中,处理内容的空格  line.rstrip()

filename1 = 'D:/python-web/pythontxt/aaa.txt'
with open(filename1, 'r') as fileobject1:
    fileaa1 = fileobject1.readlines() #读取每一行
    for line1 in fileaa1:
        print(line1)

filename2 = 'D:/python-web/pythontxt/bbb.txt'
with open(filename2,'w') as filenamea2:
    filenamea2.write("这是写入的内容") #写放文件

filename3 = 'D:/python-web/pythontxt/bbb.txt'
with open(filename3,'w') as filenamea3:
    filenamea3.write("这是写入的一行内容\n") #写入多行内容
    filenamea3.write("这是写入的第二行的内容\n")

filename4 = 'D:/python-web/pythontxt/bbb.txt'
with open(filename4,'a') as filenamea4: #符加模式
    filenamea4.write("这是写入的一行内容\n") #写入多行内容,不会覆盖
    filenamea4.write("这是写入的第二行的内容\n")

发表评论

邮箱地址不会被公开。