【发布时间】: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?感谢您的帮助。
【问题讨论】:
-
我们可以获取堆栈跟踪吗?
-
标记行似乎不太可能引发该错误。
-
您介意将答案标记为已接受还是没有答案告诉您您需要什么?
-
您好,非常感谢您的帮助。我现在标记了一个接受的答案,很抱歉回复晚了。