【问题标题】:Python: How can I open and read files in a directory that do not have a file extension (Windows)? [closed]Python:如何打开和读取没有文件扩展名的目录中的文件(Windows)? [关闭]
【发布时间】:2016-09-12 14:31:49
【问题描述】:

我目前正在编写一个脚本,该脚本将为特定字符串解析文件并将文件重命名为该字符串。但是,此脚本将处理的文件没有文件扩展名。它们在任何文本编辑器中都是可读的,但它们在其属性窗口中没有除通用“文件”类型之外的文件类型。

我已经尝试对此进行了几天的研究,但未能找到任何针对我的问题的文档。 那么有没有python方法可以打开、读取、重命名和保存没有指定文件扩展名的文件?

【问题讨论】:

  • 你试过os.rename()吗?
  • 为什么你认为扩展很重要?
  • 是否有任何 python 方法可以打开、读取、重命名和保存没有指定文件扩展名的文件? 是的,与操作具有扩展名的文件的功能相同。请参阅 File objectsos 模块。
  • @RolandSmith 我最初的尝试使用了“打开”方法来打开和读取文件。我尝试将与我的测试文件的名称(不带扩展名)匹配的字符串传递到我的脚本中,但它无法找到该文件。我已经运行相同的脚本在同一目录中查找 .txt 文件,这会产生预期的结果。
  • 啊。也许扩展名包含空格?如果你使用os.walk,如下所示,它找到所有文件。

标签: python windows file io


【解决方案1】:

您可以open()os.rename() 您有权访问的所有文件。没有扩展也没关系。


如果您不知道要重命名哪些文件,则只需打开所有文件,阅读其内容并处理与您要查找的文件匹配的文件。

import os

# Get a list of all files under the current directory
flist = []
for root, dirs, files in os.walk('.'):
    flist += [os.path.join(root, f) for f in files]

# Go over each file and see if it contains the string foo
want = 'foo'
targets = []
for path in flist:
    with open(path) as df:
        data = df.read()
    if want in data:
        targets.append(path)
# The targets list now contains the paths of all the files that contain foo.

【讨论】:

    【解决方案2】:

    看看this answer

    当您遍历文件列表时,您可以简单地检查扩展名是否为空。

    def file_has_no_extension(file_path):
        """
        Return true if and only if the file has no extension.
        """
        filename, file_extension = os.path.splitext('/path/to/somefile.ext')
    
        return not file_extension
    

    对于您的其他问题,只需查看this 之类的教程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      • 2015-08-08
      • 2020-09-12
      相关资源
      最近更新 更多