【问题标题】:Python how to check if a file is opened using notepadPython如何检查文件是否使用记事本打开
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 不适用于文本文件或使用记事本打开的文件
    猜你喜欢
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多