如何在Python中用回车替换编号行?

2024-06-30 17:01:39 发布

您现在位置: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

Tags: toin程序forinputrawcontentsload
2条回答

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

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

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()

相关问题 更多 >