python 读写文件

read()将文本文件所有行读到一个字符串中。

readline()是一行一行的读

readlines()是将文本文件中所有行读到一个list中,文本文件每一行是list的一个元素。

优点:readline()可以在读行过程中跳过特定行。

读写文件有3种方法:

第一种方法:

file1 = open("test.txt") 
file2 = open("output.txt","w") 

while True: 
    line = file1.readline() 
    #这里可以进行逻辑处理 
    file2.write('"'+line[:s]+'"'+",") 
    if not line: 
        break 
#记住文件处理完,关闭是个好习惯 
file1.close() 
file2.close() 

 

第二种方法:

文件迭代器,用for循环的方法

file2 = open("output.txt","w") 
for line in open("test.txt"): 
    #这里可以进行逻辑处理 
    file2.write('"'+line[:s]+'"'+",") 
file2.close()

第三种方法:

文件上下文管理器

with open('somefile.txt', 'r') as f: 
     data = f.read() 

# Iterate over the lines of the file 
with open('somefile.txt', 'r') as f: 
     for line in f: 
         # process line 

# Write chunks of text data 
with open('somefile.txt', 'w') as f: 
     f.write(text1) 
     f.write(text2) 
     ... 

# Redirected print statement 
with open('somefile.txt', 'w') as f: 
     print(line1, file=f) 
     print(line2, file=f) 
posted @ 2019-11-22 20:21  爱学英语的程序媛  阅读(129)  评论(0编辑  收藏  举报