向单词文件添加额外的列



我有一个看起来像这样的文本文件:

1 0.0
2 0.2
3 0.4

我现在要做的是检查某些值是否在阈值之间,然后在行中添加一些内容。因此,如果值为 0.1,因此介于 0 和 0.2 之间,则应添加"1",输出应为:

1 0.0 1
2 0.2
3 0.4

我试过这个:

#open doc
doc = "sample_name.txt"
f = open(doc, "r")
lines = l.readlines()
count = 1 
for line in lines:
elements = line.split(" ")
start_time = elements[1]
#get element from next line
next_line = lines[count]
elements_new_line = next_line.split(" ")
end_time = element_new_line[1]
if i >= end_time and i <= start_next_time:
#add a one the file
#increase counter
count = count + 1

关于如何将 1 写入.txt文件的任何想法

严格来说,在文本文件中的行尾添加值通常并不容易。这是因为即使向一行添加一个字符也涉及将文件中的所有其他字符"推"到右边。通常,首选的策略是读取输入文件的行,根据需要在这些行中添加或修改字符,并将它们写入输出文件。在您的情况下,可以丢弃输入文件,并将输出文件放在其位置。

我编写了以下代码,以便在打开输入和输出文件时使用with,以便在退出with缩进时自动关闭它们。现在,这是处理文件的首选方式。

我的假设是每行只有两个值,称为firstsecond。我使用strip删除每行末尾的任何换行符或回车符。我使用if来测试输入值。您会注意到,有必要从读取的字符转换为浮点数,以便与浮点值进行比较。

退出with存储区时,存储区中有两个文件。我丢弃原始版本并将新版本重命名为原始版本的名称。

with open('sample_name.txt') as sample, open('temp.txt', 'w') as temp:
for line in sample:
first, second = line.strip().split()
if 0 <= float(second) < 0.2:
temp.write('%s %s 1n' % (first, second))
else:
temp.write('%s %sn' % (first, second))
from os import remove, rename
remove('sample_name.txt')
rename('temp.txt', 'sample_name.txt')

写入修改后的文件,然后覆盖原始文件。

import os
fname = "sample_name.txt"
temp_fname = fname + ".tmp"
with open(fname, 'r') as fin, open(temp_fname, 'w') as fout:
for line in fin:
parts = line.split()
if 0 < float(parts[1]) < 0.2:
parts.append("1")
fout.write(' '.join(parts) + 'n')
else:
fout.write(line)
os.remove(fname)
os.rename(temp_fname, fname)

相反,如果您希望始终修改该行(在条件通过时添加一个'1',在条件未通过时添加一个'0'),请将 for 循环更改为:

for line in fin:
parts = line.split()
parts.append("1" if 0 < int(parts[1]) < 0.2 else "0")
fout.write(' '.join(parts) + 'n')

最新更新