在给定条件下使用python在文本文件中写入

时间:2016-05-20 18:56:20

标签: python

我是python中的新手,我正在尝试使用python在文本文件中编写一个给定的句子:

这是我的文件,我想在“直接”之后的行中写“T T T” 如果第三列高于给定值:

Cu Pd                                   
   3.87100000000000     
     1.0000000000000000    0.0000000000000000    0.0000000000000000
     0.0000000000000000    1.0000000000000000    0.0000000000000000
     0.0000000000000000    0.0000000000000000    1.0000000000000000
   Cu   Pd
     1     3
Selective dynamics
Direct
 -0.0042765297000522 -0.0042765297000522 -0.0042765297000522
 -0.0038509734526576  0.4960637515763522  0.4960637515763522 
  0.4960637515763522  0.4960637515763522 -0.0038509734526576
  0.4960637515763522 -0.0038509734526576  0.4960637515763522

例如:如果第三列“x”的值大于1.00,则列后将收到“T T T”,否则将收到“F F F”。

有什么建议我可以从哪里开始? 谢谢!

1 个答案:

答案 0 :(得分:0)

可能想看看这样的事情。它从一个文件读取并写入另一个文件。它只会在“直接”之后开始检查内容。遇到了。它应该让你开始如何进行。

def modFile(inPath, outPath, threshold):
    direct = False;
   try:
       # open input file
       with open(inPath, 'r') as ifp:
           # open output file
           with open(outPath, 'w', 'w') as ofp:
                # read each line.
                for line in ifp:
                    if not direct:
                        if line == 'Direct':
                            direct = True
                    else:
                        parts = line.split()
                        # check third value
                        if parts[2] > threshold:
                            line += ' T T T'
                    ofp.write(line + '\n')
    except IOError, e:
        print("Can't read or write from one of the files.")
        # handle in some way
        raise

它可能只是解决你的完整问题的起点,但应该给你一些线索。

相关问题