• 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)
  • 相关阅读:
    [bzoj1500][luogu2042][cogs339][codevs1758]维修数列(维护数列)
    无旋treap的简单思想以及模板
    [hdu2036]改革春风吹满地
    (treap)[bzoj3224][洛谷3369][cogs1829]Tyvj 1728 普通平衡树
    [bzoj3875][Ahoi2014]骑士游戏
    [bzoj1433][ZJOI2009]假期的宿舍
    <struct、union、enum>差异
    LeetCode(50) Pow(x,n)
    LeetCode(49)Group Anagrams
    LeetCode(48)Rotate Image
  • 原文地址:https://www.cnblogs.com/liujinjing521/p/11166130.html
Copyright © 2020-2023  润新知