如何解决如何用Python合并子文件夹中的文本
我有一个包含 4 个子文件夹的文件夹,我想合并每个子文件夹中的文本(换句话说,制作应该分别是 4 个合并文本,而不是统一所有子文件夹的整个文本)。 The folder is like this
我想使用 os.walk 但没有结果。
代码如下:
$select->bindValue(1,$txt,PDO::PARAM_STR);
$select->bindValue(2,PDO::PARAM_STR);
解决方法
当你走路(穿过风暴)...
您需要将文件记录到它们所在的目录中 - 事实上,当您到达 f_out.write() 行时,您的方式与阅读循环中发生的事情不同步。
试试这个:
allFiles2 = {}
for root,dirs,files in os.walk(rootdir):
for d in dirs:
f_out = open(rootdir + d + 'combined.txt','w',encoding='utf-8')
allFiles2[os.path.join(root,d)] = []
for name in files:
fullName = os.path.join(root,name)
#At this point,we want to send the file to the correct dictionary position,so use the path defining the dictionary as a search item
for key in allFiles2:
if key == fullName[:len(key)]:
allFiles2[key].append(os.path.join(root,name))
for i1 in allFiles2: #Looping through the keys (directories) in allFiles2
with open(i1 + 'combined.txt',encoding='utf-8') as f_out:
for i2 in allFiles2[i1]: #Looping through the files in that directory
if i2.endswith('.txt'):
with open(i2,'r') as f_in:
for line in f_in.readlines():
f_out.write(line)
f_out.write("\n")
现在,我不确定您希望输出的文本文件是什么形状 - 但希望这对您来说是一个有用的起点。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。