【发布时间】:2020-11-07 17:58:23
【问题描述】:
我的代码适用于 excel、word 和 PDF 等文件,但不适用于文本文件意味着我们使用记事本打开的文件,无论它是否已关闭, 操作系统:Windows 10
import os
file_location = 'C:\\Users\\Desktop\\abc.txt'
file_dir = os.path.dirname(file_location)
file_name = os.path.basename(file_location)
relative_file_location = os.path.relpath(file_location)
if os.path.exists(relative_file_location):
os.chdir(file_dir)
try:
os.rename(relative_file_location,file_name)
print('File is closed')
except OSError:
print('File is still open.')
else:
print("Path does not exist")
【问题讨论】:
标签: python file-io operating-system