我想在一个目录中的所有文本文件上运行我的脚本,但是我遇到了很多麻烦。你知道吗
以下是我目前掌握的代码:
data = {}
date = ID = values = None
infile = "z140327b.txt"
outfile = "oz140327b.txt"
sample = 1
with open(infile) as datafile, open(outfile, 'w') as f2:
for line in datafile:
if line.lstrip().startswith('!'):
date = line[1:].strip()
elif line.lstrip().startswith('?'):
sample = 2
elif line.lstrip().startswith('@'):
ID = line[1:].strip()
data[ID] = {}
data[ID]['date'] = date
tedtime = ID[0:2] + ":" + ID[2:]
str_1 = str(data[ID])
f2.write(tedtime + ' ' + date + ',' + str(sample))
elif line.strip():
if not ID:
continue
try:
words = line.split()
value = float(words[-1]) # last word
unit = words[-2].lstrip('(').rstrip(')')
item = {'value': value, 'unit': unit}
key = ' '.join(words[:-2])
data[ID][key] = item
except (ValueError) as err:
print("Could not parse this line:")
print(line)
continue
else: # if 'empty' line
ca_str = str(data[ID]['Contact Angle']['value'])
f2.write(',' + ca_str + '\n')
ID = None
ca_str2 = str(data[ID]['Contact Angle']['value'])
f2.write(',' + ca_str2 + '\n')
现在,我正在手动添加文件名(infile)和输出文件名(outfile)。我希望输出文件名与输入文件相同,前面有一个“o”,如示例代码所示。你知道吗
可以使用glob获取目录中的所有文件:
只需迭代每个文件名,做你想做的事,然后将它写入一个新文件。 确保您的脚本是从您所在的目录运行的,或者您需要将路径传递给glob。你知道吗
相关问题 更多 >
编程相关推荐