• 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)
  • 相关阅读:
    入门菜鸟
    FZU 1202
    XMU 1246
    Codeforces 294E Shaass the Great 树形dp
    Codeforces 773D Perishable Roads 最短路 (看题解)
    Codeforces 814E An unavoidable detour for home dp
    Codeforces 567E President and Roads 最短路 + tarjan求桥
    Codeforces 567F Mausoleum dp
    Codeforces 908G New Year and Original Order 数位dp
    Codeforces 813D Two Melodies dp
  • 原文地址:https://www.cnblogs.com/liujinjing521/p/11166130.html
Copyright © 2020-2023  润新知