[Python学习]Python中利用open()函数写入内容

#-*- coding:utf-8 -*-

#写入文件

filename = 'programming.txt'

with open(filename, 'w') as file_object:

    file_object.write("I love programming.\n")

with open(filename, 'r') as file_object:

    contents = file_object.read()

    print(contents.rstrip())

#写入多行

with open(filename, 'w') as file_object:

    file_object.write("I love creating games.\n")

with open(filename, 'r') as file_object:

    contents = file_object.read()

    print(contents.rstrip())

#追加内容

filename_a = 'programming_a.txt'

with open(filename_a, 'a') as file_object:

    file_object.write("I also love finding meaning in large datasets.\n")

    file_object.write("I love creating apps that can run in a browser.\n")

with open(filename_a, 'r') as file_object:

    contents = file_object.read()

    print(contents.rstrip())

#利用while循环,追加内容   

filename_b = 'guest_book.txt'

num = 0

while True:

    name = input("Please enter your name:")

    if name == 'quit':

        break

    else:

        with open(filename_b, 'a') as file_object:

            file_object.write(str(num) + ". Hello, " + name + ".\n")

        with open(filename_b, 'r') as file_object:

            contents = file_object.read()

            print(contents.rstrip())

    num += 1

你可能感兴趣的:([Python学习]Python中利用open()函数写入内容)