zoukankan      html  css  js  c++  java
  • python学习-35 文件处理

    1.简单的打开文件

    f=open('test.txt',encoding='utf-8')    # 打开了名字为test.txt的文件里的内容
    data=f.read()                            # 读取里面的内容
    print(data)
    f.close()

    运行结果:

    hello,word
    
    Process finished with exit code 0

    2.可读性

    f=open('test.txt','r',encoding='utf-8')
    data=f.readable()        # 是否可读
    print(data)
    f.close()

    运行结果:

    True
    
    Process finished with exit code 0

    3.一行一行读取内容

    f=open('test.txt','r',encoding='utf-8')
    
    print(f.readline(),end='')
    print(f.readline())
    print(f.readline())
    print(4,f.readline())
    print(5,f.readline())
    
    f.close()

    运行结果:

    1.hello,word
    2.hello,word
    
    3.hello,word
    
    4 
    5 
    
    Process finished with exit code 0

    4.读取全部内容

    f=open('test.txt','r',encoding='utf-8')
    
    
    data=f.readlines()
    print(data)
    
    f.close()

    运行结果:

    ['1.hello,word
    ', '2.hello,word
    ', '3.hello,word
    ']
    
    Process finished with exit code 0

    5.写入操作 (只能是字符串类型)

    1.

    f=open('test.txt','w',encoding='utf-8')
    
    f.write('1111
    ')    # 想换行需要加
    
    f.write('222')
    
    
    f.close()

    打开test.txt文件就会看到写入的1111和222

    2.写入列表

    f=open('test.txt','w',encoding='utf-8')
    
    f.writelines(['456
    ','123
    ','asd
    '])   
    
    
    f.close()

    可以打开自己的test.txt文件内容查看

    3.追加

    f=open('test.txt','a',encoding='utf-8')
    f.write('
    123')

    4.

    f1 = open('test.txt','r',encoding='utf-8')
    data = f1.readlines()
    f1.close()
    
    
    f2 = open('test_new.txt','w',encoding='utf-8')  # 新建一个文件
    f2.write(data[0])                # 删除除第一行外的其他行,并写入到新文件里
    f2.close()

    5.

    with open('test.txt','w') as f:       # 写入文件并自动关闭,不用手动close()
        f.write('123')

    6.从一个文件里读取到 文件 然后写入到另一个文件

    with open('test.txt','r',encoding='utf-8') as f,
        open('test_new.txt','w',encoding='utf-8') as f1:
        data = f.read()
        f1.write(data)
  • 相关阅读:
    python--binascii--二进制和ASCII编码的二进制的转换
    python--you-get视频下载
    python--AES加密
    nodejs的简单爬虫
    golang学习之接口型函数
    golang学习之defer
    golang学习之slice基本操作
    微信小程序初体验
    vuex构建笔记本应用学习
    2016年终总结
  • 原文地址:https://www.cnblogs.com/liujinjing521/p/11166130.html
Copyright © 2011-2022 走看看