python file and directory operations

python file and directory operations

Read / write file

New / Open File Write

#举个例子,打开D:\test\data.txt
#以写入模式打开文件
#如果test(上级目录)不存在则报错
#如果data.txt(文件)不存在则创建
fd = open('filename','w')
#如果文件里面已经有内容,那么内容会被清空
fd.write('stirng')
fd.close()

Open the file to read

#举个例子,打开D:\test\data.txt
#以读入模式打开文件
#如果test(上级目录)不存在则报错
#如果data.txt(文件)不存在则报错
fd = open('filename','r')
#read不传入参数,那么会读取整个文件
content = fd.read()
fd.close()

Note: open if the first argument is a string constant (manual input), then looks in the working directory, but if passed is a string variable, then the string needs to be an absolute path to the file

Directory Operations

New Directory

#例子,当前工作目录C:\test    test目录下src以及其之下的子目录python都不存在
#dirname  C:\test\src\python  
makedirs(C:\test\src\python)  #或者 makedirs(dirname)
#第一参数如果是字符串常量,那么会在工作目录中创建,但是如果是一个字符串变量,那么会生成该绝对路径(沿途不存在的路径也会创建)
#python会把以'\'分割的最后一串字符串(python)视为目录
#如果该目录已存在,那么会报错
#可提前判断一下是否存在该目录
os.path.exists('C:\test\src\python')

Browse the catalog

Mode 1

import os
#列出指定目录下的所有文件
#files 里面既包含文件名也包含目录名
files_and_dirs = os.listdir(dir)
#一般来说会用一个for循环来逐个判断
for name in files_and_dirs:
    #所以需要判断是文件还是目录,以便执行不同的操作
    #是否是目录
    #如果要遍历该路径下所有文件/目录,可以使用递归
    os.path.isdir(files_and_dirs)
    是否是文件
    os.path.isfile(files_and_dirs)

Mode 2

Direct access to all information, no manual determination

for root, dirs, files in os.walk(file_dir):  
    print(root) #当前目录路径  
    print(dirs) #当前路径下所有子目录  
    print(files) #当前路径下所有非目录子文件

Regular Expressions

import re

Here, about regular expression syntax in this little talk, mainly about how to call a regular in python

Regular use of clear purpose

Find string

#例子
source = """![1573180919937](C:\\typora-user-images\\1573180919937.png)"""

#模式串
pat = r'!\[(.+)\]\((.+)\)'
#match只匹配source字符串开头,如果前面部分无法匹配,那么就直接返回了
#search会匹配完整个source
mat_res = re.search(pat,source)
if mat_res:
    print mat_res.group()
    print mat_res.group(1)
    print mat_res.group(2)  #这里的group需要在pat中使用`()`捕获,如果没有捕获到那么调用时会报错

note:

  • If more than one group to match, then it returns only the last one

Replacement string

Embodiment 1: direct replacement, regardless of the result of the last match new_str

new_source = source.replace(mat_res.group(1),new_str)

Embodiment 2: Using a regular feature matching Alternatively, this makes it possible to use in the process alternative to the last matching results

>>> def dashrepl(matchobj):
...     if matchobj.group(0) == '-': return ' '
...     else: return '-'
#如果是'-'那么就变成空格,如果是两个'-'那么就变成一个'-'
>>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
'pro--gram files'

#当然,也支持直接替换
>>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE)
'Baked Beans & Spam'

Guess you like

Origin www.cnblogs.com/virgildevil/p/11824156.html