【问题标题】:File naming problem with PythonPython的文件命名问题
【发布时间】:2011-08-24 15:29:42
【问题描述】:

我正在尝试遍历多个 .rtf 文件并针对每个文件:读取文件,执行一些操作,然后将新文件作为与原始文件同名的纯文本文件写入子目录,但带有 .txt 扩展名。我遇到的问题是文件命名。

如果文件名为 foo.rtf,我希望子目录中的新文件为 foo.txt。这是我的代码:

import glob
import os
import numpy as np


dir_path = '/Users/me/Desktop/test/'
file_suffix = '*.rtf'
output_dir = os.mkdir('sub_dir')
for item in glob.iglob(dir_path + file_suffix):
    with open(item, "r") as infile:
        reader = infile.readlines()
        matrix = []
        for row in reader:
            row = str(row)
            row = row.split()
            row = [int(value) for value in row]
            matrix.append(row)
        np_matrix = np.array(matrix)
        inv_matrix = np.transpose(np_matrix)
        new_file_name = item.replace('*.rtf', '*.txt') # i think this line is the problem?
        os.chdir(output_dir)
        with open(new_file_name, mode="w") as outfile:
            outfile.write(inv_matrix)

当我运行这段代码时,我得到一个类型错误:

TypeError: coercing to Unicode: need string or buffer, NoneType found

如何修复我的代码以将新文件写入子目录并将文件扩展名从 .rtf 更改为 .txt?感谢您的帮助。

【问题讨论】:

  • 我们可以获取堆栈跟踪吗?
  • 标记行似乎不太可能引发该错误。
  • 您介意将答案标记为已接受还是没有答案告诉您您需要什么?
  • 您好,非常感谢您的帮助。我现在标记了一个接受的答案,很抱歉回复晚了。

标签: python mkdir


【解决方案1】:

查看 os.path 模块 (http://docs.python.org/library/os.path.html) 中的一些函数,而不是 item.replace。它们用于拆分和重新组合部分文件名。例如,os.path.splitext 会将文件名拆分为文件路径和文件扩展名。

假设您有一个文件 /tmp/foo.rtf,并且您想将其移动到 /tmp/foo.txt

old_file = '/tmp/foo.rtf'
(file,ext) = os.path.splitext(old_file)
print 'File=%s Extension=%s' % (file,ext)
new_file = '%s%s' % (file,'.txt')
print 'New file = %s' % (new_file)

或者如果你想要单行版本:

old_file = '/tmp/foo.rtf'
new_file = '%s%s' % (os.path.splitext(old_file)[0],'.txt')

【讨论】:

    【解决方案2】:

    我从未使用过 glob,但这是不使用模块的另一种方法:
    您可以使用

    轻松去除后缀
    name = name[:name.rfind('.')]
    

    然后添加新的后缀:

    name = name + '.txt'
    

    为什么不使用函数?

    def change_suffix(string, new_suffix):
        i = string.rfind('.')
        if i < 0:
            raise ValueError, 'string does not have a suffix'
        if not new_suffix[0] == '.':
            new_suffix += '.'
        return string[:i] + new_suffix
    

    【讨论】:

      【解决方案3】:

      glob.iglob() 产生路径名,不带字符“*”。 因此你的行应该是:

      new_file_name = item.replace('.rtf', '.txt') 
      

      考虑使用更清晰的名称(保留“文件名”作为文件名,使用“路径”作为文件的完整路径;使用“路径原始”而不是“项目”)、os.extsep(Windows 中的“.” ) 和 os.path.splitext():

      path_txt = os.extsep.join([os.path.splitext(path_original)[0], 'txt'])
      

      现在最好的提示: numpy 大概可以read your file directly:

      data = np.genfromtxt(filename, unpack=True)
      

      (另见here

      为了更好地了解您的 TypeError 来自哪里,请将您的代码包装在以下 try/except 块中:

      try:
          (your code)
      except:
          import traceback
          traceback.print_exc()
      

      【讨论】:

      • 对您的评论稍作更正:os.sep 在 Windows 中是 \\,而不是 .
      • 来自 glob 文档 (docs.python.org/library/glob.html#glob.glob) “路径名可以是绝对的(如 /usr/src/Python-1.5/Makefile)或相对的(如 ../../Tools/*/ *.gif),并且可以包含 shell 样式的通配符”。如果我理解正确,路径名可能包含“*”字符,但不能保证。
      • 是的:它除了通配符等。但它返回完整的路径名,所以在“项目”中,没有更多的通配符。
      猜你喜欢
      • 1970-01-01
      • 2021-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多