假设我有一个文本文件File.txt。假设它包含以下几千行:
A, B, word, C, D
“word”部分不会从一行更改为下一行,但是每隔一个字符串(此处为“A”,“B”,“C”,“D”)实际上是一个浮点值并且确实从一行到下一行。假设我有一些我定义为Q的变量(一些浮点值)。我想用S或F附加每一行。我想用S((D-4)/ 3)-A = Q±1附加一行,或者如果这是不是这样的。例如,让我们考虑以下(小规模)示例:
1, 0, text, 1, 16
2, 3, text, 3, 18.5
3, 5, text, 1, 3
4, 4, text, 55, 25
如果Q = 3,则脚本将按以下方式追加行:
1, 0, text, 1, 16, S
2, 3, text, 3, 18.5, S
3, 5, text, 1, 3, F
4, 4, text, 55, 25, S
因此,为了概括我的问题,如何使用字符串附加文本文件的每一行,该字符串取决于该行中是否满足某个条件?
答案 0 :(得分:2)
你可以将它写入另一个文件(它必须是一个不同的文件,否则这种方法不会起作用):
with open(sourcefile, mode='r') as source:
with open(targetfile, mode='w') as target:
for line in source:
A, B, word, C, D = line.split(', ')
A, B, C, D = float(A), float(B), float(C), float(D)
if -1 <= Q - (((D-4)/3)-A) <= 1:
newline = line + ', S\n'
else:
newline = line + ', F\n'
target.write(newline)
这只是检查差异是否小于1,如果你真的想检查它是否为Q + 1或Q-1那么你可以使用它:
cond = (Q+1, Q-1)
with open(sourcefile, mode='r') as source:
with open(targetfile, mode='w') as target:
for line in source:
A, B, word, C, D = line.split(', ')
A, B, C, D = float(A), float(B), float(C), float(D)
if ((D-4)/3)-A in cond:
newline = line + ', S\n'
else:
newline = line + ', F\n'
target.write(newline)
答案 1 :(得分:-1)
你可以像这样经历每一行:
for l in f.readlines():
l = l.strip('\r\n')
if l: # maybe the last line is empty
A, B, _, C, D = l.split() # extract the values
A, B, C, D = float(A), float(B), float(C), float(D) # convert from str to float
newL = l + ", " + "SF"[abs((((D-4)/3)-A) - Q) <= 1]
print(newL) # however you could pipe the output into the new file