文件相关操作File

2019-12-22  本文已影响0人  wangyu2488

2019年11月28日

一.打开文件open

image.png

1.例子 hello World

f = open('test.txt', 'w+')
f.write('world222')

f = open('test.txt', 'r+')
f.write('Hello')

f = open('test.txt', 'a')
f.write(' ')

fName = r'test.txt'
f = open(fName, 'a+')
f.write('World')
Hello222 World

二.关闭文件close() 一般用不到,如果你用 with as

# 使用finally关闭文件
f_name = 'test.txt'
try:
    f = open(f_name)
except OSError as e:
    print('打开文件失败')
else:
    print('打开文件成功')
    try:
        content = f.read()
        print(content)
    except OSError as e:
        print('处理OSError异常')
    finally:
        f.close()

# 使用with as自动资源管理
with open(f_name, 'r') as f:
    content = f.read()
    print(content)

三文件读写操作

1.文本文件读写

将a文件内容全部复制到b文件中

f_name = 'test.txt'

with open(f_name, 'r', encoding='utf-8') as f:
    lines = f.readlines()
    print(lines)
    copy_f_name = 'copy.txt'
    with open(copy_f_name, 'w', encoding='utf-8') as copy_f:
        copy_f.writelines(lines)
        print('文件复制成功')
image.png

2.二进制文件读写

f_name = 'coco2dxcplus.jpg'

with open(f_name, 'rb') as f:
    b = f.read()
    print(type(b))
    copy_f_name = 'copy.jpg'
    with open(copy_f_name, 'wb') as copy_f:
        copy_f.write(b)
        print('文件复制成功')
image.png

四.文件目录改名等相关操作,通过os模块实现

import os

f_name = 'test.txt'
copy_f_name = 'copy.txt'

with open(f_name, 'r') as f:
    b = f.read()
    with open(copy_f_name, 'w') as copy_f:
        copy_f.write(b)

try:
    os.rename(copy_f_name, 'copy2.txt')
except OSError:
    os.remove('copy2.txt')

# print(os.listdir(os.curdir))
# print(os.listdir(os.pardir))

try:
    os.mkdir('subdir')
except OSError:
    os.rmdir('subdir')

for item in os.walk('.'):
    print(item)
image.png

2.其他os 操作,判断是说是一个文件或目录等

import os.path
from datetime import datetime

f_name = 'test.txt'
af_name = r'/Users/mac/Documents/wangyu/gitRepository/HelloProj/com/pkg1/test.txt'

# 返回路径中基础名部分
basename = os.path.basename(af_name)
print(basename)  # test.txt

# 返回路径中目录部分
dirname = os.path.dirname(af_name)
print(dirname)

# 返回文件的绝对路径
print(os.path.abspath(f_name))

# 返回文件大小
print(os.path.getsize(f_name))  # 14
# 返回最近访问时间
atime = datetime.fromtimestamp(os.path.getatime(f_name))
print(atime)
# 返回创建时间
ctime = datetime.fromtimestamp(os.path.getctime(f_name))
print(ctime)
# 返回修改时间
mtime = datetime.fromtimestamp(os.path.getmtime(f_name))
print(mtime)

print(os.path.isfile(dirname))  # False
print(os.path.isdir(dirname))  # True
print(os.path.isfile(f_name))  # True
print(os.path.isdir(f_name))  # False
print(os.path.exists(f_name))  # True
image.png

如果您发现本文对你有所帮助,如果您认为其他人也可能受益,请把它分享出去。

上一篇下一篇

猜你喜欢

热点阅读