我有一组用于命名某些文件的唯一值。数组是:
import numpy as np
colors = np.array(['green','blue','red'])
在我的目录中,我有以下要迭代的文件:
我的目标是附加 _1.txt 和 _1.txt 的内容,并将新文件命名为 .txt,这是我为下面的 1 个文件所做的,但我一直坚持如何将上面的数组合并到下面的循环中:
import os
# assign directory
directory = '/home/ec2-user/SageMaker/'
# iterate over files in that directory
for filename in os.scandir(directory):
data = data2 = ""
# Reading data from file1
with open('green_1.txt') as fp:
data = fp.read()
# Reading data from file2
with open('green_2.txt') as fp:
data2 = fp.read()
# Append file2 to end of file1
data
data += data2
with open ('green.txt', 'w') as fp:
fp.write(data)```
只需添加一个内部循环colors
就可以了。此外,不要在循环中分配颜色名称,而是使用 f 字符串在迭代中输入颜色名称。
for filename in os.scandir(directory):
for color in colors:
data = data2 = ""
# Reading data from file1
with open(f'{color}_1.txt') as fp:
data = fp.read()
# Reading data from file2
with open(f'{color}_2.txt') as fp:
data2 = fp.read()
# Append file2 to end of file1
data
data += data2
with open (f'{color}.txt', 'w') as fp:
fp.write(data)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句