替换python中列表的值

时间:2015-03-25 08:54:08

标签: python list file

我正在尝试创建一个函数,它将从.txt中提取数据,格式为“样本1:1,2,7'然后替换第一个值,推动另外两个并删除最后一个。当我输入' 4'时,我希望得到以下输出:'样本1:4,1,2'但数据不会改变。我没有搜索值,因为代码遍历文件中的每一行并更改其中的特定部分。它不会取代整条生产线。

这是我的代码:

f = open("task3.txt")

lines = f.readlines()
print(lines)

for i in lines:
    splitlines = i.split(":")
    print(splitlines)
    splitnums = splitlines[1].split(", ")
    print(splitnums)
    for i in splitnums:
        i = int(i)
    edit = input('Would you like to edit this entry?')
    if edit == "Yes":
        valueNew = input("Which new value would you like to add?")
        del(splitnums[2])
        splitnums.append(splitnums[1] + "\n")
        splitnums[1] = splitnums[0]
        splitnums[0] = valueNew
        print(splitnums)
        numstring = ''.join(splitnums)
        splitlines.append(splitlines[1])
        splitlines[1] = ": "
        newval = ''.join(splitlines)
        newval = str(newval)
        i = str(i)
        print(newval)
        i.replace(i, newval)
    else:
        print("Okay.")

f.close

此外,文件中的文本不会被替换。 感谢您提供的任何帮助。

3 个答案:

答案 0 :(得分:1)

请勿使用相同的变量名。

在代码变量i中分配两个地方。在for i in lines:for i in splitnums:中,所以i是最新的商店值。所以避免这个。


使用string lower()方法。

由于我们要求用户输入Yes字词进行处理,因此最好strip并转换为lower case

演示

>>> edit = raw_input("Enter Yes to process:").strip().lower()
Enter Yes to process:             YES
>>> edit
'yes'

ALGO:  1.迭代行中的每一行。  2.要求用户通过raw_input()方法编辑或不编辑值。  3.如果是,则要求用户输入数字字符串。  4.按:拆分并获得两个不同的部分,第一个在:之前,第二个在:之后  5.通过拆分,创建第二部分列表并列出压缩以删除空格。  6.从步骤5列表中删除第二项  7.将用户值插入步骤5列表。  8.创建新行。

示例代码:

lines = ["Sample 1: 1, 2, 7", "Sample 1: 11, 12, 17" ]
new_lines = []

for line in lines:
    edit = raw_input('Would you like to edit this entry, Yes/No?').strip().lower()
    if edit== "yes":
        valueNew = raw_input("Which new value would you like to add?")
        #- Split line by :
        splitlines = line.split(":")
        print "\nDebug 1: Split Line by ':' - ", splitlines
        #- Get numners part and remove white spaces.
        splitnums = [i.strip() for i in splitlines[1].split(",")]
        print "Debug 2: Split Numbers -", splitnums
        #- Remove second element.
        del splitnums[2]
        splitnums.insert(0, valueNew)
        print "Debug 3: After adding New Number -",splitnums 
        new_line = splitlines[0]+ ":"+ ', '.join(splitnums)
        print "Debug 4: New Line -", new_line
        new_lines.append(new_line)
    else:
        new_lines.append(line)


print "\nFinal New Lines:", new_lines

输出:

infogrid@infogrid-vivek:~/workspace/vtestproject/study$ python test1.py
Would you like to edit this entry, Yes/No?yes
Which new value would you like to add?77

Debug 1: Split Line by ':' -  ['Sample 1', ' 1, 2, 7']
Debug 2: Split Numbers - ['1', '2', '7']
Debug 3: After adding New Number - ['77', '1', '2']
Debug 4: New Line - Sample 1:77, 1, 2
Would you like to edit this entry, Yes/No?no

Final New Lines: ['Sample 1:77, 1, 2', 'Sample 1: 11, 12, 17']

注意: 使用raw_input()用于Python 2.x

对Python 3.x使用input()

答案 1 :(得分:0)

您在第21行(numstring)创建了numstring = ''.join(splitnums),但未使用它来创建splitlines。此外,您似乎正在实现的看起来像一个固定长度的LIFO集合。通常,deque适合该任务。

在编辑文件时,查看fileinput模块可能会帮到你!让你开始的狙击手:

import fileinput

def process(line):
    return 'Replaced line with static text'

with fileinput.input(files=('task3.txt'), inplace=True) as f:
    for line in f:
        print(process(line))

答案 2 :(得分:0)

您的代码中不需要进行所有字符串和整数转换,并且您没有做任何事情来将数据写回文件。您可以使用[new_value] + numbers[:-1]之类的内容将新值添加到该行,然后使用.format以正确的格式将其写回文件。

with open('task3.txt') as f:
    lines = f.readlines()

with open('task3.txt', 'w') as output:
    for line in lines:
        edit = input('Would you like to edit this entry?').lower()
        if edit == 'yes':
            heading, data = line.split(':')
            numbers = data.split(', ')
            new_value = input('Which new value would you like to add?')
            numbers = [new_value] + numbers[:-1]
            output.write('{}: {}\n'.format(heading, ', '.join(numbers)))
        else:
            output.write(line + '\n')