简体   繁体   English

Python从读取文件中拆分行,然后在另一文件中以另一种格式写入它们

[英]Python split lines from read file and write them with another format in another file

I read the lines from a file which containing two columns with values in that style: 我从文件读取行,该文件包含两列具有该样式的值:

      100.E-03             5.65581E-06
      110.E-03            11.222E-06  
      120.E-03            18.3487E-06 
      130.E-03            15.6892E-06 

I need to write them in antoher file as: 我需要将它们写在另一个文件中:

          100.E-03       ,      5.65581E-06
          110.E-03       ,     11.222E-06  
          120.E-03       ,     18.3487E-06 
          130.E-03       ,     15.6892E-06 

Can I do this with split? 我可以拆分吗? Can I define spaces, for example 5 spaces as the split variable? 我可以定义空格,例如5个空格作为split变量吗? And when yes, how can I pick the splitted parts in order to write them in the way I want: My script looks like: 当是的时候,我该如何挑选分割的部分以便按照自己的方式编写它们:我的脚本如下所示:

for k in files:
    print 'k =',k
    from  abaqus import session
    print k 
    with open("niffacc{k}.inp".format(k=k)) as f1:
       with open("niffacc_{k}.inp".format(k=k),"w") as f2:
            for line in itertools.islice(f1, 4, None):
                b = line.split("            ")
                #print "b:", b
                c = b[1]
                d = b[3] 
                f2.write('%s'%c + "," + '%s'%d)    
    #with open('VY_{k}'.format(k=k), 'a') as f1:
    #lines = f1.readlines()
    f2.close()
    f1.close()

I think the problem is in defining b, the splitted line. 我认为问题出在定义b,即分割线。 Is there any problem by defining as split character the spaces? 通过将空格定义为分割字符是否存在任何问题? Does python have a problem ti split because of the many spaces or it is handled as a groups of spaces? python是否由于多个空格而出现了ti分割问题,还是将其作为一组空格处理? Is a better solution to convert the file in csv file and then back to txt file? 是一种将csv文件中的文件转换为txt文件的更好的解决方案吗?

I'm not sure why you want that many spaces between your columns but you can just split on whitespace: 我不确定为什么您想要在列之间有这么多空间,但是您只能在空白处分割:

with open('file1.txt') as f1, open('file2.txt', 'w') as f2:
    for line in f1:
        f2.write(line.split()[0] + ',' + line.split()[1] + '\n')

If you really want a bunch of spaces, then just use: 如果您真的想要一堆空格,请使用:

f2.write(line.split()[0] + '    ,    ' + line.split()[1] + '\n')

split将自动处理任意数量的空格。

'      100.E-03             5.65581E-06'.split() == ['100.E-03', '5.65581E-06']

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

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