如何从文本文件中取一个数字并将其替换为该数字+1?

时间:2017-02-09 20:03:01

标签: python

我想取一个数字,在我的情况下为0,然后加1,然后将其替换回文件。这就是我到目前为止所做的:

def caseNumber():
    caseNumber = open('caseNumber.txt', "r")
    lastCase = caseNumber.read().splitlines()[0]
    Case = []
    Case.append(lastCase)
    newCase = [ int(x)+1 for x in Case ]

    with open('caseNumber.txt', mode = 'a',
    encoding = 'utf-8') as my_file:
        my_file.write('{}'.format(newCase))

    print('Thankyou, your case number is {}, Write it down!'.format(newCase))

运行之后,我得到:

这是添加到文件中的内容:0000 [1](文件中的数字是0000  开始时,但它添加[1]以及

基本上,我坚持的部分是在没有括号的情况下将数字加1。

2 个答案:

答案 0 :(得分:3)

newCase是一个列表,打印时将其值括在括号中。如果您只想将列表中 的值写入文件,则需要说明。

答案 1 :(得分:1)

您不需要创建列表理解,因为您只需要1个项目。

由于您将列表转换为字符串,因此您将获得列表表示:带括号。

请注意,这不是唯一的问题:您要附加到文本文件(a模式),而不是替换该号码。你必须从头开始编写文件。但为此,您必须在第一次阅读时保存完整的文件内容。我的建议:

with open("file.txt") as f:
    number,_,rest = f.read().partition(" ") # split left value only
    number = str(int(number)+1)   # increment and convert back to string

with open('file.txt',"w") as f:
    f.write(" ".join([number,rest])) # write back file fully

所以如果文件包含:

0 this is a file
hello

每次运行上面的代码时,前导号都会递增,但会保留trailint文本

1 this is a file
hello

依旧......