如何在python中用返回值替换编号行



我有一个python程序,它接受一个带有信息列表的.txt文件。然后程序继续对每一行进行编号,然后删除所有返回值。现在我想在没有双间距的行中添加返回,这样我就可以继续编辑文件了。这是我的程序。

import sys
from time import sleep
# request for filename
f = raw_input('filename > ')
print ''
# function for opening file load
def open_load(text):
    for c in text:
        print c,
        sys.stdout.flush()
        sleep(0.5)
print "Opening file",
open_load('...')
sleep(0.1)
# loading contents into global variable
f_ = open(f)
f__ = f_.read()
# contents are now contained in variable 'f__' (two underscores)
print f__
raw_input("File opened. Press enter to number the lines or CTRL+C to quit. ")
print ''
print "Numbering lines",
open_load('...')
sleep(0.1)
# set below used to add numbers to lines
x = f
infile=open(x, 'r')
lines=infile.readlines()
outtext = ['%d %s' % (i, line) for i, line in enumerate (lines)]
f_o = (str("".join(outtext)))
print f_o
# used to show amount of lines
with open(x) as f:
    totallines = sum(1 for _ in f)
print "total lines:", totallines, "n"
# -- POSSIBLE MAKE LIST OF AMOUNT OF LINES TO USE LATER TO INSERT RETURNS? --
raw_input("Lines numbered. Press enter to remove all returns or CTRL+C to quit. ")
print ''
print "Removing returns",
open_load('...')
sleep(0.1)
# removes all instances of a return
f_nr = f_o.replace("n", "")
# newest contents are now located in variable f_nr
print f_nr
print ''
raw_input("Returns removed. Press enter to add returns on lines or CTRL+C to quit. ")
print ''
print "Adding returns",
open_load('...')
sleep(0.1)

这是我需要的一个例子。在我的代码中,下面没有返回(n)。我将终端设置为行的顺序,而不需要返回(n)。

1 07/07/15 Mcdonalds $20 1 123 12345
2 07/07/15 Mcdonalds $20 1 123 12345
3 07/07/15 Mcdonalds $20 1 123 12345
4 07/07/15 Mcdonalds $20 1 123 12345
5 07/07/15 Mcdonalds $20 1 123 12345

编号1-5需要用返回替换,这样每行都是它自己的行。这是编辑后的效果

# the numbering has been replaced with returns (no double spacing)
07/07/15 Mcdonalds $20 1 123 12345
07/07/15 Mcdonalds $20 1 123 12345
07/07/15 Mcdonalds $20 1 123 12345
07/07/15 Mcdonalds $20 1 123 12345
07/07/15 Mcdonalds $20 1 123 12345

根据您的输入/输出数据示例:

g = open(output_filename, 'w')
f = open(filename)
sep = ' '  # separator character
for line in f:
    L = line.split()[1:]  # remove the first item - the line number
    g.write(sep.join(L))  # rewrite the line without it
g.close()
f.close()

我已经意识到这并不能解决我的问题。-我的问题是,有返回文件的原始数据是在错误的地方。所以我写了一个程序,在取出所有返回值之前对每一行进行编号,然后我想用新的返回值替换行前的数字,以使一切正确。谢谢你们的帮助!我应该在开始之前就看到的,哈哈。

最新更新