Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 替换文本文件中的行_Python_List_File_Replace_Line - Fatal编程技术网

Python 替换文本文件中的行

Python 替换文本文件中的行,python,list,file,replace,line,Python,List,File,Replace,Line,基本上,我想做的就是简单地覆盖包含分数的文本文件中的一行,尽管在搜索了一段时间后我没有任何运气 我不知道如何将包含旧列表的“val”替换为“empty”,本质上更新文件“scores.txt”以便替换该行 index = 0 with open('scores.txt','r') as f: x = f.readlines() print(x) name = input('Enter name: ') print('\n') c_1 = 0 c

基本上,我想做的就是简单地覆盖包含分数的文本文件中的一行,尽管在搜索了一段时间后我没有任何运气

我不知道如何将包含旧列表的“val”替换为“empty”,本质上更新文件“scores.txt”以便替换该行

index = 0
with open('scores.txt','r') as f:
    x = f.readlines()
    print(x)

    name = input('Enter name: ')
    print('\n')

    c_1 = 0
    c_2 = 0
    empty = []

    for val in x:
        c_1 += 1
        print("Iteration",c_1)
        print('val',val)

        if name in val:
            print('True: ' + '"' + name + '"' , val)
            empty.append(val)

            empty = [i.split() for i in empty]
            print(empty)

            empty = [item for sublist in empty for item in sublist]
            print(empty,'\n')

            print('len empty',len(empty))

            while len(empty) > 4:
                del empty[1]
                c_2 += 1
                print("Del Iteration",c_2)

            print('empty after del',empty)

            break


        elif name not in val:
            print("False\n")
        index+=1
这是可以在“scores.txt”中看到的内容

jill 9 10 7 8 5
bob 4 6 7
denas 2 4
john 1
我的目标是将“jill”的分数减少到3分,我的代码就是这样做的,但是在退出代码并打开“scores.txt”后,可以看到更改


我知道这个问题以前已经得到了回答,但我自己无法让它工作,因为我还是Python新手://

一般来说,您需要写入一个单独的文件,然后将新文件复制到旧文件上才能做到这一点。您可以使用或修改文件,但您可以自己研究这些

例如,给出了:

$ cat /tmp/scores.txt
jill 9 10 7 8 5
bob 4 6 7
denas 2 4
john 1
您可以通过以下方式修改文件:

with open('/tmp/scores.txt', 'r') as f, open('/tmp/mod_scores.txt', 'w') as fout:
    for line in f:
        if line.startswith('jill'):
            line=' '.join(line.split()[0:4])
        fout.write(line.strip()+"\n")  
现在,您有了一个包含所需修改的文件:

$ cat /tmp/mod_scores.txt
jill 9 10 7
bob 4 6 7
denas 2 4
john 1
现在只需将新文件复制到旧文件上,即可完成。若要复制,请使用现在将文件scores.txt修改到位

根据评论,要获得最后3分和前3分,您可以执行以下操作:

with open('/tmp/scores.txt', 'r') as f, open('/tmp/mod_scores.txt', 'w') as fout:
    for line in f:
        if line.startswith('jill'):
            li=line.split()
            line=' '.join([li[0]]+li[-3:])
        fout.write(line.strip()+"\n")    

以防万一,dwag的答案是您应该使用的,以下是您的代码在修复后的工作情况:

index = 0
# empty and x must have global scope.
empty = []
x = []

with open('scores.txt','r') as f:

    x = f.readlines()
    name = input("Enter the name: ")
    c_1 = 0
    c_2 = 0
    for val in x:
        c_1 += 1
        print("Iteration",c_1)
        print('val',val)

        if name in val:
            empty.append(val)
            empty = [i.split() for i in empty]
            empty = [item for sublist in empty for item in sublist]

            while len(empty) > 4:
                del empty[1]
                c_2 += 1
            break

        elif name not in val:
            print("False")

        index += 1

with open('scores.txt','w') as f:
    x[0] = ' '.join(empty + ['\n'])
    f.writelines(x)

感谢有效的解决方案,很抱歉打扰您,但我如何更改此设置,使其从左向右删除值?请参阅编辑。使用一个切片并将两个列表添加到一起。