python学习 (三十四) Python文件操作

1 写文件

my_list = ["1", "2", "3"]

my_file = open("myfile.txt", "w")

for item in my_list:
    my_file.write(item + "\n")            
my_file.writelines(my_list) // 写多个 my_file.close()

2  读文件

my_file = open("myfile.txt", "r")
print(my_file.read())                    // 一次性读取整个文件
my_file.close()

my_file = open("myfile.txt", "r")
print(my_file.readline())                // 读一行
print(my_file.readline())                // 再读下一行
my_file.close()

 3  循环读取文件

my = open("myfile.txt")

for line in my:
    print(line + " aaa ")

 4 with ... As ...

with open("myfile.txt", "w") as with_as_writ:
    with_as_writ.write("aaa")

 


posted @ 2018-10-28 18:06  刘大飞  阅读(183)  评论(0编辑  收藏  举报