zoukankan      html  css  js  c++  java
  • Python基础:文件的基本操作

    # 打开文件(如果不存在则新建) 向其中写入
    f = open('D:\test.txt', 'w')
    f.write('hello world, i am here!')
    f.close()
    print("-" * 30)  # 分割线
    
    # 读取文件
    f = open('D:\test.txt', 'r')
    content = f.read(5)  # 最多读取5个数据
    print(content)
    
    print("-" * 30)  # 分割线
    
    content = f.read()  # 从上次读取的位置继续读取剩下的所有的数据
    print(content)
    
    f.close()  # 关闭文件
    
    print("-" * 30)  # 分割线
    # readlines可以按照行的方式把整个文件中的内容进行一次性读取,并且返回的是一个列表,其中每一行的数据为一个元素
    f = open('D:\test.txt', 'r')
    content = f.readlines()
    print(type(content))
    
    i = 1
    for temp in content:
        print("%d:%s" % (i, temp))
        i += 1
    
    f.close()
    
    print("-" * 30)  # 分割线
    # readline
    f = open('D:\test.txt', 'r')
    content = f.readline()
    print("1:%s" % content)
    
    content = f.readline()
    print("2:%s" % content)
    
    f.close()
    
    # 复制文件
    oldFileName = "D:\test.txt";
    # 以读的方式打开文件
    oldFile = open(oldFileName, 'rb')
    
    # 提取文件的后缀
    fileFlagNum = oldFileName.rfind('.')
    if fileFlagNum > 0:
        fileFlag = oldFileName[fileFlagNum:]
    
    # 组织新的文件名字
    newFileName = oldFileName[:fileFlagNum] + '[复件]' + fileFlag
    
    # 创建新文件
    newFile = open(newFileName, 'wb')
    
    # 把旧文件中的数据,一行一行的进行复制到新文件中
    for lineContent in oldFile.readlines():
        newFile.write(lineContent)
    
    # 关闭文件
    oldFile.close()
    newFile.close()
    
    # 文件重命名
    import os
    
    os.rename("D:\test.txt", "D:\test2.txt")
    
    # 删除文件
    os.remove("D:\test2.txt")
    
    # 创建文件夹
    os.mkdir("D:\alex")
    
    # 删除文件夹
    os.rmdir("D:\alex")
  • 相关阅读:
    [BZOJ]4810: [Ynoi2017]由乃的玉米田
    VK Cup 2017
    Educational Codeforces Round 19
    [BZOJ]4162: shlw loves matrix II
    2017-4-14校内训练
    第一次 CSP-S 的游记
    APIO2009 采油区域
    NOIP2017 逛公园
    NOIP2013 货车运输
    【9018:1458】征兵
  • 原文地址:https://www.cnblogs.com/blazeZzz/p/9520108.html
Copyright © 2011-2022 走看看