1

我正在尝试编辑我拥有的一些文本文件,以便为其中一列添加价值。我想在文件的第二列中添加两个新数字,并用空格分隔。第一列将在 13 个字符处结束,然后有两个空格,然后添加新的两位数字,其他列将保持不变。

我编写了以下脚本,但不幸的是它确实有效。如果有人可以帮助我找到我的错误,我将不胜感激。

%********function************
def add_num(infile,outfile):
    output = ["%s  %s%s" %(item.strip()[:13] ,32,item.strip()[16:]) for item in infile]
    outfile.write("\n".join(output))
    outfile.close()
    return outfile
%*********************************
%**********main code for calling the function*******
import os, Add32
folder = 'E:/MLS_HFT/TEST/Stuttgart_2009_pointclouds/'
for filename in os.listdir(folder):
      infilename = os.path.join(folder,filename)
      if not os.path.isfile(infilename): continue
      base,extension = os.path.splitext(filename)
      infile= open(infilename, 'r')
      outfile = open(os.path.join(folder, '{}_32{}'.format(base,extension)),'w')
      add32.add_num(infile,outfile)

这是一个数据样本:

 399299.855212  512682.330  5403021.950  303.471  64    1  1  2        75
 399299.855212  512681.470  5403020.790  302.685  1     1  2  2        75
 399299.855222  512682.360  5403021.970  303.526  79    1  1  2        76
4

4 回答 4

2

使用str.split

col = 2
#just pass filenames to your function and use `with` statement for handling files.
with open(infile) as f, open(outfile, 'w') as out:
    for line in f:
        spl = line.split(None, col)
        spl[col -1] = '32' + spl[col -1]
        out.write(" ".join(spl))
...         
399299.855212 32512682.330 5403021.950  303.471  64    1  1  2        75

399299.855212 32512681.470 5403020.790  302.685  1     1  2  2        75

399299.855222 32512682.360 5403021.970  303.526  79    1  1  2        76

您的代码的工作版本:

def add_num(infile,outfile):
   with open(infile) as f, open(outfile, 'w') as out:
      output = ["%s  %s%s\n" %(item.strip()[:13] ,32,item.strip()[16:]) for item in f]
      out.writelines(output)

outfile = os.path.join(folder, '{}_32{}'.format(base,extension))
add_num(infilename,outfile)
于 2013-06-21T15:57:12.557 回答
2
def add_num(infile,outfile):
    output = ["%s  %s%s" %(item.strip()[:13] ,32,item.strip()[16:]) for item in infile]
    outfile.write("\n".join(output))
    outfile.close()
    return outfile

add_num(open("infile.data"),open("outfile.data","w"))

然后看看 outfile.data ...你的函数没有问题,可能你是如何调用它的

于 2013-06-21T16:01:04.637 回答
1
with open('infile.txt', 'rb') as infile, open('outfile.txt', 'wb') as outfile:
    outfile.writelines(line[:15] + '32' + line[15:] for line in infile)
于 2013-06-21T16:02:53.187 回答
0

您可以使用切片表示法插入字符,例如

myString = myString[:15] + "  12" + myString[15:]

将在位置 15 插入 4 个字符

第一个切片myString[:15]将得到一个从开始到第 15 个位置的子字符串

第二个切片myString[15:]将获得从第 15 个位置到末尾的子字符串

您可以通过在中间添加字符来连接它

于 2013-06-21T15:57:49.053 回答