一、实验目的和要求
文件操作
二、实验过程
通过pycharm进行代码编辑
三、实验过程
敲代码
四、代码及其结果
实例
print("\n","="*10,"蚂蚁庄园动态","="*10)
file = open('message.txt','w') # 创建或打开保存蚂蚁庄园动态信息的文件
print("\n 即将显示……\n")
# 以下为关闭文件对象的代码
file.close() # 关闭文件对象
print("\n","="*10,"蚂蚁庄园动态","="*10)
file = open('message.txt','w') # 创建或打开保存蚂蚁庄园动态信息的文件
# 写入一条动态信息
file.write("你使用了1张加速卡,小鸡撸起袖子开始双手吃饲料,进食速度大大加快。\n")
print("\n 写入了一条动态……\n")
file.close() # 关闭文件对象
print("\n","="*25,"蚂蚁庄园动态","="*25,"\n")
with open('message.txt','r') as file: # 打开保存蚂蚁庄园动态信息的文件
message = file.read() # 读取全部动态信息
print(message) # 输出动态信息
print("\n","="*29,"over","="*29,"\n")
print("\n","="*35,"蚂蚁庄园动态","="*35,"\n")
with open('message.txt','r') as file: # 打开保存蚂蚁庄园动态信息的文件
number = 0 # 记录行号
while True:
number += 1
line = file.readline()
if line =='':
break # 跳出循环
print(number,line,end= "\n") # 输出一行内容
print("\n","="*39,"over","="*39,"\n")
import os # 导入os模块
path = "C:\\demo" # 指定要遍历的根目录
print("【",path,"】 目录下包括的文件和目录:")
for root, dirs, files in os.walk(path, topdown=True): # 遍历指定目录
for name in dirs: # 循环输出遍历到的子目录
print("●",os.path.join(root, name))
for name in files: # 循环输出遍历到的文件
print("◎",os.path.join(root, name))
import os # 导入os模块
fileinfo = os.stat("message.txt") # 获取文件的基本信息
print("文件完整路径:", os.path.abspath("mr.png")) # 获取文件的完整数路径
# 输出文件的基本信息
print("索引号:",fileinfo.st_ino)
print("设备名:",fileinfo.st_dev)
print("文件大小:",fileinfo.st_size," 字节")
print("最后一次访问时间:",fileinfo.st_atime)
print("最后一次修改时间:",fileinfo.st_mtime)
print("最后一次状态变化时间:",fileinfo.st_ctime)
实战
import os # 文件或目录模块
import time # 导入时间模块
def nsfile(s):
'''''The number of new expected documents'''
# 判断文件夹是否存在,如果不存在则创建
b = os.path.exists("F:\\1.Study_GPNU\Python\chapter10")
if b:
print("该目录存在!")
else:
os.mkdir("F:\\1.Study_GPNU\Python\chapter10")
# 生成文件
for i in range(1, s + 1):
# 获取当前系统时间
localTime = time.strftime("%Y%m%d%H%M%S", time.localtime())
# 以当前系统时间作为文件名称
filename = "F:\\1.Study_GPNU\Python\chapter10" + localTime + ".txt"
# a:以追加模式打开(必要时可以创建)append;b:表示二进制
f = open(filename, 'ab')
# 文件内写入的信息
testnote = '文件测试'
# 写入文件信息
f.write(testnote.encode('utf-8'))
f.close()
# 输出第几个文件和对应的文件名称
print("file" + " " + str(i) + ":" + str(localTime) + ".txt")
time.sleep(1) # 休眠一秒
print('生成文件成功!')
if __name__ == '__main__':
s = int(input("请输入需要生成的文件数:")) # 获取输入的文件个数
nsfile(s)
import os # 文件或目录模块
path = 'F:\\1.Study_GPNU\Python\chapter10' # 外层路径
def folder(s):
for i in range(1, s + 1):
# 设置文件夹名称
folder_name = path + str(i)
# 检测文件夹是否存在
if isExists(folder_name):
print("该目录存在!")
else:
# 不存在进行创建
os.makedirs(folder_name)
if isExists(folder_name):
print('文件夹', i, '创建成功!')
# 检测文件夹是否存在
def isExists(folder_name):
b = os.path.exists(folder_name)
return b
if __name__ == '__main__':
s = int(input("请输入需要生成的文件夹个数:")) # 获取输入的文件夹个数
folder(s)