Python学习笔记三:IO编程

文件读写

读文件:

with open('/path/to/file', 'r') as f:
    print(f.read())

调用read()会一次性读取文件的全部内容,如果文件有10G,内存就爆了,所以,要保险起见,可以反复调用read(size)方法,每次最多读取size个字节的内容。另外,调用readline()可以每次读取一行内容,调用readlines()一次读取所有内容并按行返回list。因此,要根据需要决定怎么调用。

for line in f.readlines():
    print(line.strip()) # 把末尾的'\n'删掉

写文件:

with open('/Users/michael/test.txt', 'w') as f:
    f.write('Hello, world!')

'r' 为只读模式,'w'为只写模式,'a'为附加模式

os模块

操作文件和目录的函数一部分放在os模块中,一部分放在os.path模块中

# 查看当前目录的绝对路径:
>>> os.path.abspath('.')
'/Users/michael'
# 在某个目录下创建一个新目录,首先把新目录的完整路径表示出来:
>>> os.path.join('/Users/michael', 'testdir')
'/Users/michael/testdir'
# 然后创建一个目录:
>>> os.mkdir('/Users/michael/testdir')
# 删掉一个目录:
>>> os.rmdir('/Users/michael/testdir')

os.path.split():拆分路径,把一个路径拆分为两部分,后一部分总是最后级别的目录或文件名

os.path.splitext():可以直接让你得到文件扩展名

>>> os.path.split('/Users/michael/testdir/file.txt')
('/Users/michael/testdir', 'file.txt')
>>> os.path.splitext('/path/to/file.txt')
('/path/to/file', '.txt')

文件操作:

# 对文件重命名:
>>> os.rename('test.txt', 'test.py')
# 删掉文件:
>>> os.remove('test.py')

编写一个程序,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径。

# 在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径。

import os

def query(pathstr,querystr):
  for x in os.listdir(path=pathstr):
      abspath =os.path.join(pathstr,x)
      if os.path.isfile(abspath):
          if querystr in x:
              print(abspath)
      if os.path.isdir(abspath):
          query(abspath,querystr)

query(r"D:\python_work","io")

猜你喜欢

转载自blog.csdn.net/yaoliuwei1426/article/details/80757605