程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

[Python]从零开始学python——Day05 文件操作

发布于2019-09-02 13:25     阅读(486)     评论(0)     点赞(24)     收藏(4)


1.文件操作

1.1 打开关闭文件

r = open('demo01.txt','r')

r.close()

1.1.1 访问模式

r : 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。

w : 打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。

a : 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。

b : 二进制模式,换行符原样写入读出,不转换

rb : 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。

wb : 以二进制格式打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。

ab : 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。

r+ : 打开一个文件用于读写。文件指针将会放在文件的开头。

w+ : 打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。

a+ : 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。

rb+: 以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。

wb+: 以二进制格式打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。

ab+: 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。

1.2 写数据 write

w = open('demo01.txt','a+')

w.write("\nhey,i have opened the file")

w.close()

1.3 读数据 read

read(num) 读取num个字节的数据,如果没有

r = open('demo01.txt','r')

content = r.read()

print(content)

r.close()

1.4 读数据行 readlines

按行将数据一次性读取,返回一个列表

r = open('demo01.txt','r')

content = r.readlines()

i = 1
for temp in content:
    print("%d:%s"%(i,temp))
    i += 1
r.close

1.5 读数据行 readline

读一行数据

r = open('demo01.txt','r')

i = 1
while True:
    #读一行数据
    content = r.readline() 
    #如果读到最后一行,就停止
    if content is None or content == '':
        break;
    print("%d:%s"%(i,content))
    i+=1

r.close()

1.6 制作文件的备份

import os
from datetime import datetime


# 遍历打印指定文件夹下所有子文件夹和文件
def eachPath(path,targetPath):

    # 获取指定目录下的文件夹和文件名字
    pathDir = os.listdir(path)
    for childDir in pathDir:

        # 拼接成完整路径
        child = os.path.join(path,childDir)
        targetChild = os.path.join(targetPath,childDir)
        print(child)
        print(targetChild)

        # 如果目标是文件夹,创建文件夹
        if os.path.isdir(targetChild):
            os.makedirs(targetChild)

        # 如果是文件,复制
        if os.path.isfile(child):
            copyFile(child,targetChild)

        # 如果是文件夹,递归
        else:
            eachPath(child,targetChild)



# 给文件加时间戳
def timestampsAdd(fileName):

    # 1.提取文件的后缀
    fileFlagIndex = fileName.rfind(".")
    # 找不到返回-1
    if fileFlagIndex < 0:
        return;
    fileFlag = fileName[fileFlagIndex:]

    # 2.获取原文件名
    oldFileName = fileName[:fileFlagIndex]

    #构造新文件的名字   原文件名+时间戳+原文件后缀
    newFileName = oldFileName+datetime.now().strftime("%Y%m%d")+fileFlag

    return newFileName



def copyFile(filePath,targetPath):

    # 如果是文件,才复制
    if os.path.isfile(filePath):

        # 获取目标文件夹
        fileNameIndex = targetPath.rfind("\\")
        if fileNameIndex < 0:
            return;
        targetDir = targetPath[:fileNameIndex+1]
        if not os.path.exists(targetDir):
            os.makedirs(targetDir)

        # 把旧文件中的数据,一行行复制到新文件中
        oldFile = open(filePath,'rb')
        newFile = open(targetPath,'wb')
        for content in oldFile.readlines():
            newFile.write(content)

        # 关闭文件
        oldFile.close()
        newFile.close()



path = "E://work//jc//iwms-hn//trunk"
targetPath = 'E://备份//jc//jc'

timeStampsFlag = datetime.now().strftime("%Y%m%d")
targetPath = targetPath+timeStampsFlag
if not os.path.exists(targetPath):
    os.makedirs(targetPath)

eachPath(path,targetPath)

1.7 获取当前读写的位置

f = open("E:\\123.txt")
print(f.read(11))
print(f.tell())  #11
f.close()

1.8 定位到某个位置

seek(offset,from)

注:seek只支持二进制文件,所以要用b模式打开

offset:偏移量

from:方向
    0   :表示文件开头
    1   :表示当前位置
    2   :表示文件末尾
f = open("E:\\123.txt",'rb')

# 重新设置位置:离文件末尾,三字节处
f.seek(-3,2)

print(f.read())

f.close()

1.9 重命名 os.rename(old.new)

默认位置是当前代码所在的目录

import os

os.rename("123.txt","abc.txt")

1.10 删除 os.remove(file)

import os

os.remove("abc.txt")

1.11 创建文件夹 os.mkdir(doc)

注:如果文件夹已经存在,会报错

import os

createDoc = '123'
if not os.path.exists(createDoc):
    os.mkdir(createDoc)

1.12 获取当前目录

import os

currentDoc = os.getcwd()

print(currentDoc)

1.13 改变默认目录

import os

os.chdir("../")

print(os.getcwd())

1.14 获取目录列表

返回的是列表

import os

print(os.listdir())

1.15 删除文件夹

import os

print(os.rmdir('123'))

1.16 批量给文件添加时间戳

"""
批量给文件添加时间戳
"""
import os
from datetime import datetime

'''
flag : 1 添加时间戳; 0  删除时间戳
'''
def timestampAdd(path,flag):

    if os.path.exists(path):
        os.chdir(path)
        dirlist = os.listdir()

        for content in dirlist:
            # 如果是文件,进行添加删除时间戳操作
            if os.path.isfile(content):
                pointIndex = content.rfind(".")
                timeIndex = content.find("_")

                # 添加时间戳
                if flag == 1:
                    mark = datetime.now().strftime("_%Y%m%d")
                    # 文件之前没有时间戳,插入时间戳
                    if timeIndex < 0:
                        newFile = content[:pointIndex] + mark + content[pointIndex:]
                    # 文件之前有时间戳,更新时间戳
                    else:
                        newFile = content[:timeIndex] + mark + content[pointIndex:]
                else:
                    # 文件有时间戳,删除
                    if timeIndex >= 0:
                        newFile = content[:timeIndex] + content[pointIndex:]
                    # 文件没有时间戳,不变
                    else:
                        newFile = content
                # 重命名文件
                os.rename(content,newFile)

            else:
                # 递归
                timestampAdd(content,flag)
                # 递归完,将os的当前目录调回之前的目录
                os.chdir("../")

path = 'C:\\Users\\admin\\Documents\\com\\jc\\idgenerator'
timestampAdd(path,1)


所属网站分类: 技术文章 > 博客

作者:遥远的她

链接:https://www.pythonheidong.com/blog/article/79136/7b2e28e29eb35a534ee3/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

24 0
收藏该文
已收藏

评论内容:(最多支持255个字符)