python - Python如何检查文件是否使用记事本打开
问题描述
我的代码适用于 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")
解决方案
这将检查文件是否打开。如果是,那么您可以对文件执行任何操作。如果它碰巧被关闭,如果您尝试打开它,它会给您一个错误。所以我只是除了错误。希望这会有所帮助。
try:
myfile = open("myfile.csv", "r+") # or "a+", whatever you need
except IOError:
print "Could not open file! Please close Excel!"
with myfile:
do_stuff()
推荐阅读
- php - 更好地使用 Wordpress 主题 Mod
- php - Array_push 不生成新键,而是替换当前值
- node.js - 错误 eslint@5.6.0:引擎“节点”与此模块不兼容。尝试创建反应应用程序时
- unity3d - Google Play 游戏服务登录时应用程序崩溃
- javascript - Twilio:无法连接到 Live:信号连接已断开
- javascript - Next.js 中具有嵌套组件路由渲染功能的等效路由?
- curly-braces - Magento 2标签翻译显示大括号
- c++ - 如何修复 xychart.cpp 中的“index < m_series->count()”错误?
- sql - SQL 将两个表合并为下两个表,其中每个表具有重复的不同值
- javascript - 如何在 node.js 中为不同的环境定义不同的变量?