首页 > 解决方案 > 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")

标签: pythonfile-iooperating-system

解决方案


这将检查文件是否打开。如果是,那么您可以对文件执行任何操作。如果它碰巧被关闭,如果您尝试打开它,它会给您一个错误。所以我只是除了错误。希望这会有所帮助。

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()

推荐阅读