我有一个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
答案 0 :(得分:0)
根据您的输入/ ouptut数据样本:
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()
答案 1 :(得分:0)
我意识到这不会解决我的问题。 - 我的问题是文件的原始数据中存在错误位置的返回。因此,在我取出所有返回值之前,我编写了一个程序来对每一行进行编号,然后我想用新的返回值替换行前面的数字,以使一切正确。谢谢你所有人的帮助!在我开始之前,我应该已经看过了,哈哈。