简体   繁体   English

从文件读取值,更新值并写回文件-Python

[英]Reading values from a file, updating values, and writing back to file - Python

I have a CSV file containing different parameters and results for a test, that looks like the following: 我有一个包含不同参数和测试结果的CSV文件,如下所示:

Val1  Val2  Val3  Val4  Pass  Fail  Result
   1     1     1     1     0     0       0
   3     5     6    14     0     0       0

What I would like to do is read the line from the file (neglecting the first line, of course), run the test, then repeatedly update the 'Pass', 'Fail', and 'Result' part of the line. 我想做的是从文件中读取该行(当然忽略第一行),运行测试,然后重复更新该行的“通过”,“失败”和“结果”部分。 Some pseudocode/real code to help explain some more: 一些伪代码/真实代码可以帮助解释更多内容:

def readfile():
  fp = open('foo.csv', 'r+')
  lines = fp.readlines()[1:]
  for i in range(0, len(lines)):
      line = lines[i]
      # depending on test result, Pass or Fail will be updated, here Pass will be updated
      line[4] += 1
      # write line[4] back to file
      # keep updating the Pass or Fail until a condition is met then go to next line

Is there a way to do this, and would it also be possible that the file mode I'm using wouldn't allow this? 有没有办法做到这一点,还有可能我正在使用的文件模式不允许这样做吗?

I have too low a rep to comment so here is my comment as an answer. 我的代表回复太低,所以这是我的评论。 What if you used two files. 如果使用了两个文件怎么办。 One for your input values and one for your output results for your test. 一种用于输入值,另一种用于测试的输出结果。 Then in your loop you could locally hold the values of pass, fail and result incrementing them until your condition is met and at that time write the result line to the output file. 然后,在循环中,您可以本地保存pass,fail和值的结果,并递增它们直到满足您的条件,然后将结果行写入输出文件。 An index or just row number could be used to keep the results and the input in files correlated. 索引或仅行号可用于使结果与文件中的输入保持关联。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM