目录
一、文件 *** 作
1.1 打开文件
1.1.1 open()函数
1.1.2 with方式打开文件:会默认关闭文件
1.1.3 chardet检测文件编码
1.1.4 文件 *** 作模式
1.1.5 文件对象
1.2 文件 *** 作常用方法
1.2.1 read()
1.2.2 readlines()
1.2.3 readline()
1.2.4 write()
1.2.5 writelines()
1.2.6 close()关闭文件
1.2.7 flush()刷新文件的内部缓冲区,并写入文件
1.2.8 fileno()返回长整型的文件描述符
1.2.9 isatty()判断file是否是一个类tty设备
1.2.10 tell()返回当前在文件中的位置
1.2.11 seek(off, whence=0)在文件中移动文件指针,从whence偏移off字节
1.2.12 truncate(size=file.tell())截取文件到最大size字节,默认为当前文件位置
1.2.13 linecache模块
1.3 序列化:pickle模块
1.4 扩展知识
1.4.1 相对路径和绝对路径
二、目录 *** 作
2.1 os
2.1.1 os.getcwd()
2.1.2 os.chdir()
2.1.3 os.name
2.1.4 os.mkdir(path [, mode=0777])
2.1.5 os.makedirs(path [, mode=0777])
2.1.6 os.listdir()
2.1.7 os.curdir
2.1.8 os.pardir
2.1.9 os.removedirs(path)
2.1.10 os.rmdir(path)
2.1.11 os.remove(filePath)
2.1.12 os.rename(oldname, newname)
2.1.13 os.stat(path)
2.1.14 os.utime(path[, (atime, mtime)])
2.1.15 os.system (command)
2.1.16 os.sep
2.1.17 os.linesep
2.1.18 os.pathsep
2.1.19 os.environ()
2.1.20 os.access()
2.1.21 os.chmod(path, mode)
2.1.22 os.popen(command [, mode='r' [, bufsize]])
2.1.23 os.walk(top, topdown=True, οnerrοr=None, followlinks=False)
2.2 os.path
2.2.1 os.path.abspath(path)
2.2.2 os.path.split(path)
2.2.3 os.path.dirname(path)
2.2.4 os.path.basename(path)
2.2.5 os.path.exists(path)
2.2.6 os.path.isabs(path)
2.2.7 os.path.isfile(path)
2.2.8 os.path.isdir(path)
2.2.9 os.path.normpath(path)
2.2.10 os.path.getsize(name)
2.2.11 os.path.join(a, *p)
2.2.12 os.path.splitext(path)
2.2.13 os.path.splitdrive(path)
2.2.14 os.path.getatime
2.2.15 os.path.getctime
2.2.16 os.path.getmtime
2.3 sys模块
2.3.1 sys.argv
2.3.2 sys.exit()
2.4 shutil模块
2.4.1 复制文件/目录
2.4.2 移动/删除文件(目录)
三、课堂练习
3.1、读入一组数字,然后把每组数字加1后输出,比如123,输出234
3.2、删除一个字符串中的小写字母
3.3、100以内大于5的数字输出
3.4、函数参数传入5个字母,声明一个可变参数的函数,拼成一个单词
3.5、把自己的名字+编号写10次到文件中
3.6、统计文件的行数、包含英文的行数
3.7、处理数据文件
3.8、建一个10级嵌套目录,每一级目录名字为gloryroad1-10,每个目录下有一个同名的txt文件,文件内容也同名
3.9、判断某个目录下有多少个文件和目录,如果有txt文件,请删除掉
3.10 将文件名的数字乘以10后,将文件重新命名
一、文件 *** 作 1.1 打开文件 1.1.1 open()函数
作用:用来打开一个文件,成功打开文件后会返回一个文件对象,否则引发一个IOError异常
语法: File_object= open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) ➢ file: 文件名称。 ➢ mode: 制定了文件打开的方式,函数提供了如下方式,其中, ' r'为默认方式。 ➢ buffering:如果可选参数buffering的值被设置为0,就不会有缓存;如果值为1,访问文件时会缓存一行数据;如果值为大于1的整数,代表使用给定值作为缓冲区大小;如果不提供该参数或取负值,代表使用系统默认缓冲机制。 ➢ encoding:编码或者解码方式。默认编码方式依赖平台,如果需要特殊设置,可以参考codecs模块,获取编码列表 ➢ errors: 可选,并且不能用于二进制模式,指定了编码错误的处理方式,可以通过codecs.Codec获得编码 错误字符串 ➢ mode: 制定了文件打开的方式,函数提供了如下方式,其中,'rt'为默认方式。 ➢newline:换行控制,参数有:None,‘\n’,‘\r’,‘\r\n’。 读取文件时,如果参数为None,那么行结束的标志可以是:‘\n’,‘\r’,‘\r\n’任意一个,并且三个控制符都首先会被转化为:‘\n‘; 写入文件时,如果不设置newline参数,那么写入内容中的任何’\n’都会被翻译成当前系统的line separator(也就是os.linesep),如果参数为‘’或者‘\n’,不会有任何变化。 如果newline是任何其他的合法输入值,'\n'会被翻译成相应的值。 ➢ closefd: false:文件关闭时,底层文件描述符仍然为打开状态,这是不被允许的,所以,需要设置为ture ➢ opener: 可以通过调用*opener*方式,使用自定义的开启器。底层文件描述符是通过调用*opener*或者 *file*, *flags*获得的。 ➢ *opener*必须返回一个打开的文件描述。将os.open作为*opener*的结果,在功能上,类似于通过None。>>> fp=open(r"F:\python_day8\p1.txt","w+",encoding="gbk")
>>> print(type(fp))
>>> print(fp)
<_io.TextIOWrapper name='F:\python_day8\p1.txt' mode='w+' encoding='gbk'>
>>> fp_content = ""
>>> for i in range(10):
... fp_content += "glory road测试" + str(i) + "\n"
...
>>> fp.write(fp_content)
120
>>> fp.close()
>>> fp = open(r"F:\python_day8\p1.txt","r","gbk")
Traceback (most recent call last):
File "", line 1, in
TypeError: 'str' object cannot be interpreted as an integer
>>> fp = open(r"F:\python_day8\p1.txt","r",encoding="gbk")
>>> print(fp.readlines())
['glory road测试0\n', 'glory road测试1\n', 'glory road测试2\n', 'glory road测试3\n', 'glory road测试4\n', 'glory road测试5\n', 'glory road测试6\n', 'glory road测试7\n', 'glory road测试8\n', 'glory road测试9\n']
>>> fp.close()
# 手动将p1.txt文件更改为utf-8编码后
>>> fp = open(r"F:\python_day8\p1.txt","r",encoding="utf-8")
>>>
>>> print(fp.read())
glory road测试0
glory road测试1
glory road测试2
glory road测试3
glory road测试4
glory road测试5
glory road测试6
glory road测试7
glory road测试8
glory road测试9
# windows下默认使用gbk读取文件
>>> fp = open(r"F:\python_day8\p1.txt","r")
>>> print(fp.read())
glory road娴嬭瘯0
glory road娴嬭瘯1
glory road娴嬭瘯2
glory road娴嬭瘯3
glory road娴嬭瘯4
glory road娴嬭瘯5
glory road娴嬭瘯6
glory road娴嬭瘯7
glory road娴嬭瘯8
glory road娴嬭瘯9
# 在p1.txt中加入生僻字时,会报错
>>> fp = open(r"F:\python_day8\p1.txt","r")
>>> print(fp.read())
Traceback (most recent call last):
File "", line 1, in
UnicodeDecodeError: 'gbk' codec can't decode byte 0xa6 in position 236: illegal multibyte sequence
1.1.2 with方式打开文件:会默认关闭文件
>>> with open("p7.txt") as fp:
... print(fp.read())
...
hello
tty
loryroad
xxxxxxx
aaaaaaa
xxxxxxx
with的实现机制
class Sample:
def __enter__(self):# 准备的时候干什么事儿,返回的结果存在as后面的变量里面
print("In __enter__()")
return "Foo"
# with主体代码结束后需要做的事情
def __exit__(self, type, value, trace):
print("In __exit__()")
def get_sample():
return Sample() # 返回了类的实例
# with的实现机制:上下文管理机制
with get_sample() as sample:
print("sample:", sample)
1.1.3 chardet检测文件编码
文件内容需至少大于10个字符,不然可能检测的编码不准确
>>> import chardet
>>> fp = open(r"F:\python_day8\p1.txt","rb")
>>> content = fp.read()
>>> type(content)
>>> chardet.detect(content)
{'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}
1.1.4 文件 *** 作模式
模式 | 描述 | 说明 |
r | 以只读方式打开文件,这是默认模式。 |
|
rb | 以二进制格式打开一个文件用于只读 | |
r+ | 打开一个文件用于读写 | |
rb+ | 以二进制格式打开一个文件用于读写 | |
w | 打开一个文件只用于写入。 |
|
wb | 以二进制格式打开一个文件只用于写入 | |
w+ | 打开一个文件用于写读 | |
wb+ | 以二进制格式打开一个文件用于读写 | |
a | 打开一个文件用于追加 |
|
ab | 以二进制格式打开一个文件用于追加。 | |
a+ | 打开一个文件用于读写。 | |
ab+ | 以二进制格式打开一个文件用于追加 |
# 同时写读w+
>>> fp = open("p7.txt","w+") # 文件不存在时,创建文件;文件存在时,清空文件
>>> fp.write("gloryroad\n")
10
>>> fp.write("gloryroad\n")
10
>>> fp.seek(0,0)
0
>>> fp.readline()
'gloryroad\n'
>>> fp.readline()
'gloryroad\n'
>>> fp.readline()
''
>>> fp.seek(0,0)
0
>>> fp.write("HelloKitty\n") # 此时会覆盖之前的内容
11
>>> fp.seek(0,0)
0
>>> fp.read()
'HelloKitty\nloryroad\n'
>>> fp.close()
# 同时读写r+
>>> fp = open("p7.txt","r+") # 文件不存在时会报错
>>> fp.readline()
'HelloKitty\n'
>>> fp.readline()
'loryroad\n'
>>> fp.readline()
''
>>> fp.seek(0,0)
0
>>> fp.write("hello\n") # 会覆盖之前的内容
6
>>> fp.seek(0,0)
0
>>> fp.read()
'hello\ntty\nloryroad\n'
>>> fp.close()
# 追加写
>>> fp = open("p7.txt","a+")
>>> fp.readline()
''
>>> fp.seek(0,0)
0
>>> fp.readline()
'hello\n'
>>> fp.readline()
'tty\n'
>>> fp.readline()
'loryroad\n'
>>> fp.write("aaaaaaa\n")
8
>>> fp.seek(0,0) # 就算把游标移动到最前面,也会再文件最后开始写
0
>>> fp.write("xxxxxxx\n")
8
>>> fp.seek(0,0)
0
>>> fp.read()
'hello\ntty\nloryroad\naaaaaaa\nxxxxxxx\n'
>>> fp.close()
1.1.5 文件对象
底层文件描述符是一个数字,类似于句柄。一个文件被打开后,你就会得到一个文件描述符,然后就可以得到有关该文件的各种信息
属性 | 描述 |
file.closed | 返回true如果文件已被关闭,否则返回false |
file.mode | 返回被打开文件的访问模式 |
file.name | 返回文件的名称 |
>>> pic1=open("pic-1.jpg","rb")
>>> print(pic1.closed)
False
>>> print(pic1.mode)
rb
>>> print(pic1.name)
pic-1.jpg
>>> pic1.close()
>>> print(pic1.closed)
True
>>> print(pic1.mode)
rb
>>> print(pic1.name)
pic-1.jpg
>>>
1.2 文件 *** 作常用方法
1.2.1 read()
fileObject.read(size=-1, /)
➢ size为读取的长度,以byte为单位(可换行读取内容)。如果不指定参数,表示一次性读取全部内容,以字符串形式返回,并且每一行结尾会有一个"\n"符号
fileObject.readlines( hint=-1, /)
➢ 把文件每一行作为一个list的一个成员,是一个字符串,并且结尾会有一个换行符“\n”,并返回这个list。这个函数的内部是通过循环调用readline()来实现的。如果指定了hint参数,表示读取文件的字节长度,超过一行长度时候,可能会读取下一行
fileObject.readline(size=-1, /)
➢ 读取一行,如果给定了size,有可能返回的只是一行的一部分,以字符串的形式返回,并且结尾会有一个换行符"\n"。读完一行,文件 *** 作标记移动到下一行的开头。
>>> fp=open("p5.txt","r")
>>> fp.read()
'黎扶澈1\n黎扶澈2\n黎扶澈3\n黎扶澈4\n黎扶澈5\n黎扶澈6\n黎扶澈7\n黎扶澈8\n黎扶澈9\n黎扶澈10\n'
>>> fp.read()
''
>>> fp.seek(0,0)
0
>>> fp.readlines()
['黎扶澈1\n', '黎扶澈2\n', '黎扶澈3\n', '黎扶澈4\n', ' 黎扶澈5\n', '黎扶澈6\n', '黎扶澈7\n', '黎扶澈8\n', '黎 扶澈9\n', '黎扶澈10\n']
>>> fp.seek(0,0)
0
>>> fp.readline()
'黎扶澈1\n'
>>> fp.readline()
'黎扶澈2\n'
>>> fp.readline()
'黎扶澈3\n'
>>> content = fp.readline()
>>> while content:
... print(content)
... content = fp.readline()
...
黎扶澈4
黎扶澈5
黎扶澈6
黎扶澈7
黎扶澈8
黎扶澈9
黎扶澈10
>>> fp.seek(0,0)
0
>>> for line in fp:
... print(line)
...
黎扶澈1
黎扶澈2
黎扶澈3
黎扶澈4
黎扶澈5
黎扶澈6
黎扶澈7
黎扶澈8
黎扶澈9
黎扶澈10
1.2.4 write()
fileObject.write( str )
➢ 把含有文本数据或二进制数据块的字符串写到文件中,默认是不加换行符的,所以如果想换行的话,得手动加入换行符'\n
1.2.5 writelines()
fileObject.writelines( seq )
➢ 把seq(序列)的内容全部写到文件中(多行一次性写入)。也不会自动加入换行符。
注意:序列中的内容也必须是字符串类型的数据,才能成功写入文件。
>>> fp = open("p8.txt","w")
>>> fp.writelines(["gloryroad1\n","gloryroad2\n","this is a test","文件 *** 作"])
>>> fp.close()
"""
文件内容:
gloryroad1
gloryroad2
this is a test文件 *** 作
"""
1.2.6 close()关闭文件
刷新缓冲区里任何还没写入的信息,并关闭该文件,不能再进行写入。用 close()方法关闭文件是一个很好的习惯。如果文件关闭后,还对文件进行 *** 作就会产生ValueError错误,但如果不及时关闭文件,有可能产生句柄泄露,丢失数据。而且不关闭文件的话占资源,浪费句柄数量,句柄数量有限 。
1.2.7 flush()刷新文件的内部缓冲区,并写入文件>>> testList = ['test1\n', 'test2\n', 'test3', '文件 *** 作']
>>> fp = open( "bb.txt",'w+')
>>> print (fp.read(),end="\n")
>>> fp.writelines(testList)
>>> fp.flush()
>>> fp1 = open( "bb.txt",'r')
>>> print (fp1.read(),end="\n")
test1
test2
test3文件 *** 作
>>> fp.close()
>>> fp1.close()
1.2.8 fileno()返回长整型的文件描述符
>>> fp = open("p8.txt","r")
>>> print(fp.fileno())
3
>>> fp.close()
1.2.9 isatty()判断file是否是一个类tty设备
>>> fp = open("p8.txt","r")
>>> fp.isatty()
False
>>> fp.close()
1.2.10 tell()返回当前在文件中的位置
>>> fp = open("p8.txt","r")
>>> help(fp.tell)
Help on built-in function tell:
tell() method of _io.TextIOWrapper instance
Return current stream position.
>>> fp.readline()
'gloryroad1\n'
>>> fp.tell()
12
>>> fp.seek(10,0)
10
>>> fp.tell()
10
>>> fp.read(8)
'\ngloryro'
>>> fp.tell()
19
>>> fp.close()
1.2.11 seek(off, whence=0)在文件中移动文件指针,从whence偏移off字节
whence=0,代表文件其始
whence=1,代表当前位置
whence=2,代表文件末尾
注意:
- 如果文件以a或a+的模式打开,每次进行写 *** 作时,文件 *** 作标记会自动返回到文件末尾
- 文件必须是以二进制形式打开的才能以当前位置或末尾为参考位置进行定位。
>>> fp = open("p8.txt","r")
>>> fp.read()
'gloryroad1\ngloryroad2\nthis is a test文件 *** 作'
>>> fp.seek(-5,1) # 以文本形式打开的文件,以当前位置为参考位置移动文件指针时报错
Traceback (most recent call last):
File "", line 1, in
io.UnsupportedOperation: can't do nonzero cur-relative seeks
>>> fp = open("p8.txt","rb")
>>> fp.read()
b'gloryroad1\r\ngloryroad2\r\nthis is a test\xce\xc4\xbc\xfe\xb2\xd9\xd7\xf7'
>>> fp.seek(-5,1)
41
>>> fp.tell()
41
>>> fp.seek(2,1)
43
>>> fp.read()
b'\xd9\xd7\xf7'
>>> fp.seek(-20,2)
26
>>> fp.tell()
26
>>> fp.read()
b'is is a test\xce\xc4\xbc\xfe\xb2\xd9\xd7\xf7'
>>> fp.close()
1.2.12 truncate(size=file.tell())截取文件到最大size字节,默认为当前文件位置
把文件裁成规定的大小,默认的是裁到当前文件 *** 作标记的位置。如果size比文件的大小还要大,依据系统的不同可能是不改变文件,也可能是用0把文件补到相应的大小,也可能是以一些随机的内容加上去。
>>> fp=open("p8.txt","r+")
>>> fp.readline()
'gloryroad1\n'
>>> fp.tell()
12
>>> fp.read()
'gloryroad2\nthis is a test文件 *** 作'
>>> fp.seek(12,0)
12
>>> fp.truncate() # 默认size=file.tell(),即是当前位置
12
>>> fp.seek(0,0)
0
>>> fp.read()
'gloryroad1\n'
>>> fp.close()
# 截取图片
>>> pic1=open("pic-1-cp.jpg","rb+")
>>> pic1.truncate(20) # 截取后pic-1-cp.jpg图片打不开了
20
>>> pic1.close()
1.2.13 linecache模块
linecache 模块允许从任何文件里得到任何的行,并且使用缓存进行优化,常见的情况是从单个文件读取多行。
linceche 是用 utf-8 的格式处理文件 ,但是文件的编码格式为cp936,所以需要把linecache处理文件格式设置为cp936再执行以下 *** 作。 linecache.tokenize.detect_encoding = lambda _: ('cp936', []) linecache.getlines(filename) ➢ 从名为 filename 的文件中得到全 部内容,输出为列表格式,以文件 每行为列表中的一个元素,并以 linenum-1 为元素在列表中的位置存储 linecache.clearcache() ➢ 清除缓存 文件 *** 作常用方法 --linecache 模块 linecache.checkcache(filename) ➢ 检查缓存的有效性。如果在缓存中的文件在硬盘上发生了变化,并且你 需要更新版本,使用这个函数,执行此函数会将淘汰的内容删除。如果 省略 filename,将检查缓存里的所有条目。 ➢ 不是每次通话都检查。 linecache.updatecache(filename) ➢ 更新文件名为 filename 的缓存。如果 filename 文件更新了,使用这 个函数可以更新linecache.getlines(filename)返回的列表。如果出错,则返回空列表。>>> import linecache
>>> linecache.tokenize.detect_encoding = lambda _: ('cp936', [])
>>> file_content = linecache.getlines("p9.txt") #所有文件内容以列表的形式缓存到内存
>>> print(file_content)
['测试行1\n', '测试行2\n', '测试行3\n', '测试行4\n', '第6行是空行\n', '\n', '测试行7\n']
>>> file_content = linecache.getlines("p9.txt")[0:4]
>>> file_content
['测试行1\n', '测试行2\n', '测试行3\n', '测试行4\n']
>>> file_content = linecache.getline("p9.txt",2) #读取指定行
>>> file_content
'测试行2\n'
>>> # 手动修改文件内容,加入8、9、10行内容
>>> file_content = linecache.getlines("p9.txt") #再次读取到的内容未更新
>>> file_content
['测试行1\n', '测试行2\n', '测试行3\n', '测试行4\n', '第6行是空行\n', '\n', '测试行7\n']
>>> linecache.checkcache("p9.txt") # 检查缓存:如果在缓存中的文件在硬盘上发生了变化,此函数会将淘汰的内容删除
>>> file_content = linecache.getlines("p9.txt") # 再次读取,内容被更新
>>> file_content
['测试行1\n', '测试行2\n', '测试行3\n', '测试行4\n', '第6行是空行\n', '\n', '测试行7\n', '测试行8\n', '测试行9\n', 'testtesttest\n']
>>> # 再次手动更新文件内容,把8、9行变成一个空行
>>> linecache.updatecache("p9.txt") # 更新缓存,如果文件更新了,返回更新后的getlines的值
['测试行1\n', '测试行2\n', '测试行3\n', '测试行4\n', '第6行是空行\n', '\n', '测试行7\n', '\n', 'testtesttest\n']
>>> file_content = linecache.getlines("p9.txt")
>>> file_content
['测试行1\n', '测试行2\n', '测试行3\n', '测试行4\n', '第6行是空行\n', '\n', '测试行7\n', '\n', 'testtesttest\n']
>>> # 再次手动更新文件内容,加入11、12行
>>> linecache.clearcache() # 清除缓存
>>> file_content = linecache.getlines("p9.txt") # 读取到最新内容
>>> file_content
['测试行1\n', '测试行2\n', '测试行3\n', '测试行4\n', '第6行是空行\n', '\n', '测试行7\n', '\n', 'testtesttest\n', '测试行11\n', '测试行12\n']
1.3 序列化:pickle模块
python中的对象是不能保存的,关闭程序后所有的变量或者对象都没有了。持久地储存对象(序列化)可以在一个文件中储存任何Python对象,之后又可以把它完整无缺地取出来。
使用场景:用文件的方式存储数据,或者不同系统之间交换数据时使用
注意:load时必须按dump时的先后顺序,没有办法判断反序列化之后的类型,所以必须要指定dump时的顺序,而且时先进先出
F:\python_day8>py
Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> fp=open("p10.txt","wb")
>>> a=100
>>> b=[1,2,3]
>>> pickle.dump(a,fp)
>>> pickle.dump(b,fp)
>>> fp.close()
>>> ^Z
F:\python_day8>py
Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> fp=open("p10.txt","rb")
>>> a=pickle.load(fp) #必须顺序读取,若先运行b=pickle.load(fp),那么b=100
>>> a
100
>>> b=pickle.load(fp)
>>> b
[1, 2, 3]
>>> fp.close()
1.4 扩展知识
1.4.1 相对路径和绝对路径
1、相对路径:就是相对于自己的目标文件的位置。(指以当前文件所处目录而言文件的位置)————以引用文件之间网页所在位置为参考基础,而建立出的目录路径。因此当保存于不同目录的网页引用同一个文件时,所使用的路径将不相同,故称之为相对。
2、绝对路径:是指文件在硬盘上真正存在的路径。(指对站点的根目录而言某文件的位置)————以web站点为根目录为参考基础的目录路径,之所以成为绝对,意指当所有网页引用同一文件时,所引用的路径都是一样的。
>>> fp = open(r"F:\python_day8\p2.txt","w",encoding="gbk")
>>> content=""
>>> for i in range(10):
... content += "监控数据焚枯食淡吉林科技老师打开来加快" + str(i)
...
>>> fp.write(content)
200
>>> fp.close()
>>> import os
>>> os.getcwd()
'F:\\python_day8'
# 可直接读取p2.txt
>>> fp=open(r"p2.txt","rb")
>>> os.chdir("c:\\")
>>> os.getcwd()
'c:\\'
参考文章:相对路径和绝对路径的区别
二、目录 *** 作os模块提供了统一的 *** 作系统接口函数,python中对文件和文件夹的 *** 作都要涉及到os和shutil模块,在使用前需要使用import引入,例如;
import os
import os.path
import shutil
>>> import os
>>> os.name
'nt'
>>> # 获取当前系统名称
>>> os.getcwd()
'F:\\python_day8'
>>> os.chdir("f:\\")
>>> os.getcwd()
'f:\\'
>>> os.chdir('f:')#错误的写法,不会切换路径
>>> os.getcwd()
'F:\\python_day8'
2.1.4 os.mkdir(path [, mode=0777])
创建单级目录,在windows中没有mode权限一说,在linux才有
>>> os.mkdir("testdir")
>>> os.mkdir("testdir") # 当目录已存在时,再次创建会报错
Traceback (most recent call last):
File "", line 1, in
FileExistsError: [WinError 183] 当文件已存在时,无法创建该文件。: 'testdir'
>>> os.listdir()
['20160215000148.txt', '20160215000153.txt', '20160216000120.txt', '20160216000121.txt', '20160217000139.txt', '20160217000143.txt', 'bb.txt', 'data.log', 'p1.py', 'p1.txt', 'p10.txt', 'p2.py', 'p2.txt', 'p3.py', 'p3.txt', 'p4.py', 'p4.txt', 'p5.py', 'p5.txt', 'p6.py', 'p6.txt', 'p7.py', 'p7.txt', 'p8.py', 'p8.txt', 'p9.py', 'p9.txt', 'pic-1-cp.jpg', 'pic-1.jpg', 'testdir', 'with.py']
2.1.5 os.makedirs(path [, mode=0777])
创建多级目录,父目录如果不存在,递归生成。生成的目录权限默认为777.如果重复创建会出错
os.makedirs("testdir\dir1\dir2\dir3")
2.1.6 os.listdir()
列出指定目录下的所有文件和子目录,包括隐藏文件或目录,并以列表形式返回。path不写的话默认为当前目录
2.1.7 os.curdir获取当前路径,也就是('.')
2.1.8 os.pardir返回当前目录的父目录('..')
>>> import os
>>> os.curdir
'.'
>>> os.pardir
'..'
>>> os.chdir("f:\\光荣之路\\课堂编码练习")
>>> os.getcwd()
'f:\\光荣之路\\课堂编码练习'
>>> os.chdir("..")
>>> os.getcwd()
'f:\\LiFuChe\\光荣之路'
>>> os.chdir(os.pardir)
>>> os.getcwd()
'f:\\'
2.1.9 os.removedirs(path)
删除多级目录,目录为空才能删除,递归到上一级为空才能删除,不为空的话没有任何影响
os.removedirs("testdir1\dir1\dir2\dir3")
2.1.10 os.rmdir(path)
删除单级目录,不为空无法删除,会报错
>>> os.rmdir("testdir")
Traceback (most recent call last):
File "", line 1, in
OSError: [WinError 145] 目录不是空的。: 'testdir'
2.1.11 os.remove(filePath)
删除指定文件,并且只能删除文件
>>> os.remove("pic-1-cp.jpg")
>>> os.remove("pic-1-cp.jpg")
Traceback (most recent call last):
File "", line 1, in
FileNotFoundError: [WinError 2] 系统找不到指定的文件。: 'pic-1-cp.jpg'
>>> os.remove("testdir")
Traceback (most recent call last):
File "", line 1, in
PermissionError: [WinError 5] 拒绝访问。: 'testdir'
2.1.12 os.rename(oldname, newname)
重命名文件/目录
2.1.13 os.stat(path)获取文件信息,比如文件大小/创建时间/修改时间等等
>>> os.rename("bb.txt","b2b.txt")
>>> os.stat("b2b.txt")
os.stat_result(st_mode=33206, st_ino=9570149208293619, st_dev=680907193, st_nlink=1, st_uid=0, st_gid=0, st_size=27, st_atime=1650936310, st_mtime=1650936310, st_ctime=1650936310)
2.1.14 os.utime(path[, (atime, mtime)])
修改文件的时间属性,设置文件的access and modified time
2.1.15 os.system (command)运行shell命令
缺点:1)返回值只包含命令执行状态,不包含命令输出
2)阻塞 在执行os.system函数的时候通常会阻塞它的调用者,等待所启动的命令行程序退出。 在Linux平台上 只需要在命令末尾加上shell后台运算符&即可。
>>> import os
>>> os.system("dir")
驱动器 F 中的卷是 Data
卷的序列号是 2895-D1B9
F:\光荣之路\课堂编码练习\python_day8 的目录
2022/04/26 11:44 .
2022/04/26 11:44 ..
2022/04/26 10:27 36 20160215000148.txt
2022/04/26 10:27 51 20160215000153.txt
2022/04/26 10:27 36 20160216000120.txt
2022/04/26 10:27 51 20160216000121.txt
2022/04/26 10:27 36 20160217000139.txt
2022/04/26 10:27 49 20160217000143.txt
2022/04/26 09:25 27 b2b.txt
2022/04/26 10:16 343 data.log
2022/04/26 11:11 10 gloryroad1.txt
2022/04/25 08:34 532 p1.py
2022/04/25 09:08 262 p1.txt
2022/04/26 11:15 363 p10.py
2022/04/26 10:27 27 p10.txt
2022/04/25 08:22 144 p2.py
2022/04/25 09:25 390 p2.txt
2022/04/25 08:35 46 p3.py
2022/04/25 10:21 776 p3.txt
2022/04/25 08:40 250 p4.py
2022/04/25 10:48 619 p4.txt
2022/04/25 10:06 147 p5.py
2022/04/25 10:07 91 p5.txt
2022/04/25 10:49 1,220 p6.py
2022/04/25 10:48 619 p6.txt
2022/04/26 08:06 674 p7.py
2022/04/26 08:05 49 p7.txt
2022/04/26 10:23 166 p8.py
2022/04/26 09:39 12 p8.txt
2022/04/26 10:32 514 p9.py
2022/04/26 10:08 94 p9.txt
2020/06/02 22:21 169,402 pic-1.jpg
2022/04/26 11:15 testdir
2022/04/26 08:24 447 with.py
31 个文件 177,483 字节
3 个目录 493,319,553,024 可用字节
0
>>> os.system("ver")
Microsoft Windows [版本 10.0.19044.1645]
0
2.1.16 os.sep
输出 *** 作系统的特定的路径分隔符。 Win下为“\”,Linux下为“/”
2.1.17 os.linesep输出当前平台使用的行终止符,win 下为“\r\n”,Linux下为“\n”,Mac使用 '\r'。
2.1.18 os.pathsep输出环境变量路径的分割字符串,POSIX 上是 ':',Windows 上是 ';'。在 os.path 中也可用。
>>> os.sep
'\\'
>>> os.pathsep
';'
>>> os.linesep
'\r\n'
2.1.19 os.environ()
获取系统环境变量,返回的是字典
>>> os.environ['os']
'Windows_NT
2.1.20 os.access()
输出文件权限模式
>>> os.access("p9.txt",os.W_OK)
True
>>> os.access("p9.txt",os.R_OK)
True
>>> os.access("p9.txt",os.X_OK)
True
W写,R读,X可执行,输出True,False。
2.1.21 os.chmod(path, mode)修改文件或路径权限
path -- 文件名路径或目录路径。 flags -- 可用以下选项按位或 *** 作生成, 目录的读权限表示可以获取目录里文件名列 表,执行权限表示可以把工作目录切换到 此目录 ,删除添加目录里的文件必须同时有 写和执行权限 ,文件权限以用户id->组id- >其它顺序检验,最先匹配的允许或禁止权限 被应用 stat.S_IXOTH: 其他用户有执行权0o001 stat.S_IWOTH: 其他用户有写权限0o002 stat.S_IROTH: 其他用户有读权限0o004 stat.S_IRWXO: 其他用户有全部权限(权限掩码)0o007 stat.S_IXGRP: 组用户有执行权限0o010 stat.S_IWGRP: 组用户有写权限0o020 stat.S_IRGRP: 组用户有读权限0o040 stat.S_IRWXG: 组用户有全部权限(权限掩码)0o070 stat.S_IXUSR: 拥有者具有执行权限0o100 stat.S_IWUSR: 拥有者具有写权限0o200 stat.S_IRUSR: 拥有者具有读权限0o400 stat.S_IRWXU: 拥有者有全部权限(权限掩码)0o700 stat.S_ISVTX: 目录里文件目录只有拥有者才可删除更改0o1000 stat.S_ISGID: 执行此文件其进程有效组为文件所在组0o2000 stat.S_ISUID: 执行此文件其进程有效用户为文件所有者0o4000 stat.S_IREAD: windows下设为只读 stat.S_IWRITE: windows下取消只读 2.1.22 os.popen(command [, mode='r' [, bufsize]])运行一个shell命令打开一个管道,并且返回一个文件对象。然后通过 *** 作文件的方式去 *** 作这个返回值即可
参数:
command -- 使用的命令。
mode -- 模式权限可以是 'r'(默认) 或 'w'。
bufsize -- 指明了文件需要的缓冲大小:0意味着无缓冲;1意味着行缓冲;其它正值表示使用参数大小的缓冲(大概值,以字节为单位)。负的bufsize意味着使用系统的默认值,一般来说,对于tty设备,它是行缓冲;对于其它文件,它是全缓冲。如果没有改参数,使用系统的默认值。
返回值:返回一个文件描述符号为fd的打开的文件对象
>>> dirList = os.popen('ipconfig')
>>> for i in dirList.readlines():
... print(i)
...
2.1.23 os.walk(top, topdown=True, οnerrοr=None, followlinks=False)
参数说明:
➢top:表示需要遍历的目录树的路径。
➢topdown的默认值是“True”,表示首先返回目录树下的文件,然后遍历目录树下的子目录。值设为False时,则表示先遍历目录树下的子目录,返回子目录下的文件,最后返回根目录下的文件。
➢onerror的默认值是“None”,表示忽略文件遍历时产生的错误。如果不为空,则提供一个自定义函数提示错误信息后继续遍历或抛出异常中止遍历。
➢该函数返回一个列表,列表中的每一个元素都是一个元组,该元组有3个元素,分别表示每次遍历的路径名,目录列表和文件列表。
➢默认情况下,os.walk 不会遍历软链接指向的子目录,若有需要请将followlinks设定为true(软连接:类似与window的快捷方式)
import os
import os.path
dir_count=0
file_count=0
txt_file_count=0 # 统计有多少个txt文件
for root,dirs,files in os.walk("f:\LiFuChe\光荣之路\课堂编码练习\python_day8",topdown=False):
print("当前目录:", root) #打印目录绝对路径
for file in files: # 遍历某一个目录中的所有文件名称
print("文件名:", os.path.join(root,file)) # 打印文件的绝对路径
file_count += 1
if os.path.splitext(file)[1] == ".txt":
txt_file.count += 1
for dir in dirs: #遍历某一个目录中的所有子目录
print("目录名:", os.path.join(root,dir)) # 打印目录的绝对路径
dir_count += 1
print("***"*10)
print("子目录个数:",dir_count)
print("文件个数:",file_count)
2.2 os.path
2.2.1 os.path.abspath(path)
返回规范化的绝对路径名,根据当前工作目录路径连接该文件名后所组成的新的路径名,但这个路径不一定是真实存在的路径。
>>> import os.path
>>> os.path.abspath("p9.txt")
'F:\\光荣之路\\课堂编码练习\\python_day8\\p9.txt'
2.2.2 os.path.split(path)
将path分割成目录和文件名,如果给的path本身就是目录的话,也会将最后一个目录作为文件名而分离,同时它不会判断文件或目录是否存在,以元组返回
>>> os.path.split("F:\\光荣之路\\课堂编码练习\\python_day8\\p9.txt")
('F:\\光荣之路\\课堂编码练习\\python_day8', 'p9.txt')
>>> os.path.split("F:\\光荣之路\\课堂编码练习\\python_day8") # 如果给的path本身就是目录的话,将最后一个目录作为文件名而分离
('F:\\光荣之路\\课堂编码练习', 'python_day8')
>>> os.path.split("F:\\aa\\bb\\cc.txt") # 不会判断文件或目录是否存在
('F:\\aa\\bb', 'cc.txt')
2.2.3 os.path.dirname(path)
返回path的目录路径,就是os.path.split(path)的第一个元素。
2.2.4 os.path.basename(path)返回path最后的文件名。如果path以/或\结尾,就会返回空值。即os.path.split(path)的第二个元素
>>> os.path.dirname("F:\\光荣之路\\课堂编码练习\\python_day8\\p9.txt")
'F:\\光荣之路\\课堂编码练习\\python_day8'
>>> os.path.basename("F:\\光荣之路\\课堂编码练习\\python_day8\\p9.txt")
'p9.txt'
>>> os.path.dirname("f:\\aa\\bb\\cc\\dd.txt") # 也不判断文件或目录是否存在
'f:\\aa\\bb\\cc'
>>> os.path.basename("f:\\aa\\bb\\cc\\dd.txt")
'dd.txt'
2.2.5 os.path.exists(path)
判断path是否存在,如果存在返回True,否则返回False。比如新建文件的时候可以使用
2.2.6 os.path.isabs(path)判断path是否是绝对路径,如果是返回True,否则返回False。
2.2.7 os.path.isfile(path)判断path是否是文件,如果是返回True,否则返回False。必须是真实存在的文件
2.2.8 os.path.isdir(path)判断path是否是目录,如果是目录返回True,否则返回False。必须是真实存在的目录
>>> os.path.exists("f:\\aa\\bb\\cc\\dd.txt")
False
>>> os.path.exists("p9.txt")
True
>>> os.path.isabs("ab.txt")
False
>>> os.path.isabs("F:\\LiFuChe\\光荣之路\\课堂编码练习\\python_day8\\p9.txt")
True
>>> os.path.isfile("F:\\LiFuChe\\光荣之路\\课堂编码练习\\python_day8\\p9.txt")
True
>>> os.path.isdir("F:\\LiFuChe\\光荣之路\\课堂编码练习\\python_day8\\")
True
>>> os.path.isdir("F:\\LiFuChe\\光荣之路\\课堂编码练习\\python_day8\\p9.txt")
False
>>> os.path.isfile("f:\\aa\\bb\\cc\\dd.txt")
False
2.2.9 os.path.normpath(path)
将path转换成规范的文件路径
>>> os.path.normpath("c:/a/b/c.txt")
'c:\\a\\b\\c.txt'
2.2.10 os.path.getsize(name)
获得文件大小,如果name是目录返回结果是0L或者4096L;如果name代表的目录或文件不存在,会报WindowsError异常
>>> os.path.getsize("p9.txt")
94
2.2.11 os.path.join(a, *p)
连接两个或更多的路径名拼接成绝对路径,中间以“\”分隔,如果所给的参数中都是绝对路径名,那先给的绝对路径将会被丢弃。
>>> os.path.join("f:\\test","a.txt")
'f:\\test\\a.txt'
>>> os.path.join("f:\\test","d:\\a.txt")
'd:\\a.txt'
>>> os.path.join("f:\\test","hello","a.txt")
'f:\\test\\hello\\a.txt'
2.2.12 os.path.splitext(path)
分离文件名与扩展名
>>> os.path.splitext("f:\\a\\b\\c.txt")
('f:\\a\\b\\c', '.txt')
2.2.13 os.path.splitdrive(path)
拆分驱动器(盘符)和文件路径,并以元组返回结果;主要针对win有效,Linux元组第一个总是空
>>> os.path.splitdrive("f:\\a\\b\\c.txt")
('f:', '\\a\\b\\c.txt')
>>> os.path.splitdrive("c.txt")
('', 'c.txt')
2.2.14 os.path.getatime
返回文件的最后访问时间,返回的是时间戳
2.2.15 os.path.getctime以时间戳的形式返回文件或目录的创建时间,在Unix系统上是文件最近更改的时间,在Windows上是文件或目录的创建时间。
2.2.16 os.path.getmtime以时间戳的形式返回文件或目录的最后存取时间
import os
import time
#获取文件最后访问时间
lastTime = os.path.getatime("p11.py")
print(lastTime)
#将时间戳转成时间元组
formatTime = time.localtime(lastTime)
print(formatTime)
#格式化时间元组为时间字符串
print(time.strftime('%Y-%m-%d %H:%M:%S',formatTime))
#获取文件创建时间
lastTime = os.path.getctime("p11.py")
print(lastTime)
#将时间戳转成时间元组
formatTime = time.localtime(lastTime)
print(formatTime)
#格式化时间元组为时间字符串
print(time.strftime('%Y-%m-%d %H:%M:%S',formatTime))
#获取文件最后存取时间
lastTime = os.path.getmtime("p11.py")
print(lastTime)
#将时间戳转成时间元组
formatTime = time.localtime(lastTime)
print(formatTime)
#格式化时间元组为时间字符串
print(time.strftime("%Y-%m-%d %H:%M:%S",formatTime))
2.3 sys模块
2.3.1 sys.argv
交互模式下传入的命令行参数,第0个是文件名。将自己的程序发布给别人使用时,无需打开文件,直接从命令行参数输入数据,简单方便。
import sys
print(sys.argv)
def add(*arg):
result = 0
for i in arg:
if i.isdigit():
result += int(i)
return result
print(add(*sys.argv)) # 等价于add("p12.py","1","2","3")
import sys
import requests
def get_content(url):
res = requests.get(url)
return res.text[:50]
for i in sys.argv:
if "http" in i:
print(get_content(i))
对命令行输入的参数进行不同的处理
#coding=utf-8
import os,sys
def readfile(filename):
'''Print a file to the standard output.'''
f = open(filename)
while True:
line = f.readline()
if len(line) == 0:
break
print (line,)
f.close()
if len(sys.argv) ==2 and sys.argv[1].startswith('--'):
pass
elif len(sys.argv) <3:
print ('No action specified.')
sys.exit()
for id,i in enumerate(sys.argv):
print ("第%s个参数:%s" %(id,i))
if sys.argv[1].startswith('--'):
option = sys.argv[1][2:]
# fetch sys.argv[1] but without the first two characters
if option == 'version':
print('Version 1.2')
elif option == 'help':
print('''"
This program prints files to the standard output.
Any number of files can be specified.
Options include:
--version : Prints the version number
--help : Display this help''')
else:
print('Unknown option.')
sys.exit()
else:
for filename in sys.argv[1:]:
readfile(filename)
2.3.2 sys.exit() 退出当前程序
终止当前进程:sys.exit(0); sys.exit(1) # 非正常退出 2.4 shutil模块
shutil模块可以方便的移动/复制/删除目录及文件。
2.4.1 复制文件/目录import shutil
shutil.copyfile( src, dst) #src复制到dst中去。前提是目标地址是具备可写权限。抛出的异常信息为 IOException. 如果当前的dst已存在的话就会被覆盖掉
shutil.copy( src, dst) # 复制一个文件到一个文件或一个目录 shutil.copy("d:\\a.py","d:\\yy.py")
shutil.copy2( src, dst) #在copy上的基础上再复制文件最后访问时间与修改时间,类似于cp –p的东西
三者的区别:
shutil.copyfile(src,dst) # dst必须到文件名,复制成功的文件创建时间、最近修改时间、最近访问时间都是程序运行时间
shutil.copy(src,dst) # dst可以传目录,复制成功的文件创建时间、最近修改时间、最近访问时间都是程序运行时间
shutil.copy2(src,dst)# dst可以传目录,复制成功的文件创建时间为程序运行时间,最近修改时间、最近访问时间都是拷贝的src文件的最近修改时间、最近访问时间
shutil.copytree( olddir, newdir, True/Flase) #把olddir拷贝一份newdir,olddir和newdir都只能是目录,且newdir 必须不存在。如果第3个参数是True,则复制目录时将保持文件夹下的符号连接,如果第3个参数是False,则将在复制的目录下生成物理副本来替代符
2.4.2 移动/删除文件(目录)shutil.move( src, dst) #移动文件或重命名 shutil.move("d:\\aaa","d:\\ddd")
shutil.rmtree( src ) 递归删除一个目录以及目录内的所有内容,并且删除后不能恢复
三、课堂练习 3.1、读入一组数字,然后把每组数字加1后输出,比如123,输出234num_str = input("请输入一组数据:")
num_list = list(num_str)
len_num_list = len(num_list)
result = []
for i in num_list:
result.append(str(int(i)+1))
print("".join(result))
# 方法2
for i in range(len_num_list):
num_list[i] = str(int(num_list[i])+1)
print("".join(num_list))
# 方法3
result = int(num_str) + int("1"*len_num_list)
print(result)
# 方法4
result = 1
for i in range(len_num_list-1):
result = result * 10 + 1 # 也可以用result= 0, result += pow(10,i)
print(int(num_str)+result)
3.2、删除一个字符串中的小写字母
s = input("请输入字符串:")
new_s = ""
for i in s:
if not (i >= "a" and i <= "z"):
new_s += i
print("删除小写字母后:",new_s)
3.3、100以内大于5的数字输出
for i in range(0,101):
if i > 5:
print(i)
3.4、函数参数传入5个字母,声明一个可变参数的函数,拼成一个单词
def join_letters(*args):
return "".join(args)
# 方法2
# result = ""
# for i in args: # args的类型是一个元组args=("a","b")
# result += i
# return result
print(join_letters("a","b"))
print(join_letters("a","b","c","d","e"))
3.5、把自己的名字+编号写10次到文件中
>>> fp=open("p5.txt","w")
>>> for i in range(1,11):
... fp.write("黎扶澈" + str(i) + "\n")
...
5
5
5
5
5
5
5
5
5
6
>>> fp.flush()
>>> fp.close()
3.6、统计文件的行数、包含英文的行数
1)统计一个文件的行数
2)统计一下文件中不算空行的行数
3) 统计一下文件中包含英文字母的行数
4)统计一下文件中包含英文字母的个数
5)将文件中所有的包含英文字母的行去掉
import string
fp = open("p3.txt","r")
content = fp.readlines()
# 1、统计一个文件的行数
print("文件总行数:",len(content))
# 2、统计一下文件中不算空行的行数
lines = 0
for i in content:
if i != "\n":
lines += 1
print("文件中不算空行的行数:",lines)
# 3、统计一下文件中包含英文字母的行数
letter_lines=0
for i in content:
for j in i:
if j in string.ascii_letters:
letter_lines += 1
break
print("文件中包含英文字母的行数:",letter_lines)
# 4、统计一下文件中包含英文字母的个数
letter_count = 0
for i in content:
for j in i:
if j in string.ascii_letters:
letter_count += 1
print("文件中包含英文字母的个数:",letter_count)
# 5、将文件中所有的包含英文字母的行去掉
for i in content:
for j in i:
if j in string.ascii_letters:
content.remove(i)
break
fp2 = open("p4.txt","w")
fp2.write("".join(content))
fp2.close()
# 方法2
# fp3 = open("p6.txt","w")
# for i in content:
# for j in i:
# if "a"<=j<="z" or "A"<=j<="Z":
# break
# else: # i这一行都没有英文字母的时候,写文件
# fp3.write(i)
# fp3.close()
fp.close()
3.7、处理数据文件
数据需求:每行内容需要生成以每行首年月日为名称的文件,文件内容写入|0|后的所有行内容(也包括|0| )
数据文件:data.log
20160215000148|0|collect info job start|success|
20160215000153|0|collect info job end|success|resultcode = 0000
20160216000120|0|collect info job start|success|
20160216000121|0|collect info job end|success|resultcode = 0000
20160217000139|0|collect info job start|success|
20160217000143|0|collect info job end|success|resultcode = 0000
算法分析:
➢ 遍历每一行,每行取头14个字母
➢ 新建文件,文件名为首14个字母,然后把第15字符后的所有字符拷贝到文件中
➢ 关闭文件
fp = open("data.log","r")
lines = fp.readlines()
for line in lines:
with open("%s.txt" % line[:14],"w") as outfp:
outfp.write(line[14:])
print("写入完成")
3.8、建一个10级嵌套目录,每一级目录名字为gloryroad1-10,每个目录下有一个同名的txt文件,文件内容也同名
import os
os.chdir("testdir")
for i in range(1,11):
dir_name = "gloryroad" + str(i)
os.mkdir(dir_name)
os.chdir(dir_name)
with open(dir_name+".txt","w") as fp:
fp.write(dir_name)
print("创建目录完成")
3.9、判断某个目录下有多少个文件和目录,如果有txt文件,请删除掉
base_dir_name="p11dir"
file_count = 0
dir_count = 0
l = os.listdir()
for i in l:
if os.path.isfile(i):#如果是文件
file_count += 1
if i[-4:] == ".txt": #删除txt文件
os.remove(i)
elif os.path.isdir(i):#如果是目录
dir_count += 1
print("%s目录下一共有:%d个目录,%d个文件" %(base_dir_name,dir_count,file_count))
3.10 将文件名的数字乘以10后,将文件重新命名
# 2)将txt文件中的行数,做一个总的统计,且不统计空行
import os
import os.path
line_count=0
for root,dirs,files in os.walk(r"F:\LiFuChe\光荣之路\课堂编码练习\python_day8\test", topdown=False):
for file in files:
file_name = os.path.splitext(file)[0]
post_fix_file_name = os.path.splitext(file)[1]
# 改文件名
old_file_path = os.path.join(root,file)
new_file_path = os.path.join(root,str(int(file_name)*10)+post_fix_file_name)
# os.rename(old_file_path,new_file_path)
# os.rename(file,str(int(file_name)*10)+post_fix_file_name) # 使用相对路径会报FileNotFoundError错
print("*"*20)
# 统计txt文件的行数
file_path = os.path.join(root,file)
if post_fix_file_name == ".txt":
fp=open(file_path,encoding="utf-8")
content = fp.readlines()
for line in content:
if line.strip()!="": # line != "\n":
line_count += 1
fp.close()
print(content)
print("txt文件的总行数:",line_count)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)