zoukankan      html  css  js  c++  java
  • 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) 
  • 相关阅读:
    在不给spring管理的类中获取类
    poi操作excel
    闭包
    输入url的过程发生了什么?
    跨域
    函数节流-防抖函数
    预解析-案例
    移动端适配方案
    实现元素水平居中和垂直居中的几种方法
    css小知识点
  • 原文地址:https://www.cnblogs.com/Bella2017/p/11913881.html
Copyright © 2011-2022 走看看