美文网首页
python 文件操作

python 文件操作

作者: 蜗牛会跑步 | 来源:发表于2020-03-09 15:39 被阅读0次

    读写文件通常包含以下操作:

    • 打开文件。获取文件对象

    • 读写文件、对文件内容进行操作。

    • 关闭文件。使用文件对象关闭文件。

      参数设置.png

    a、读取整个文件内容

    # 打开文件
    files = open(r"C:\Users\zhuji\Desktop\python\.vscode\filetest.txt",encoding='utf-8')
    # 修改文件内容
    text=files.read()
    print(text)
    # 关闭文件
    files.close()
    
    这是一个测试文件
    用来测试python的文件操作
    存储为txt格式
    

    b、按行读取文件

    # 打开文件
    files = open(r"C:\Users\zhuji\Desktop\python\.vscode\filetest.txt",encoding='utf-8')
    # 修改文件内容
    while True:
        text=files.read()
        if not text:
            break
        print(text)
    # 关闭文件
    files.close()
    
    这是一个测试文件
    用来测试python的文件操作
    存储为txt格式
    

    c、复制文件

    # 打开文件
    files1 = open(r"C:\Users\zhuji\Desktop\python\.vscode\filetest.txt",encoding='utf-8')
    files2= open(r"C:\Users\zhuji\Desktop\python\.vscode\filetest[复件].txt",'w',encoding='utf-8')
    # 修改文件内容
    while True:
        text=files1.read()
        if not text:
            break
        files2.write(text)
    # 关闭文件
    files1.close()
    files2.close()
    
    result.png

    相关文章

      网友评论

          本文标题:python 文件操作

          本文链接:https://www.haomeiwen.com/subject/gdspdhtx.html