首页 > 解决方案 > 如何在使用文件中的组件时覆盖文件?

问题描述

我无法获得我想要的输出。我不确定如何解决这个问题,因为每次我运行代码时都没有得到任何输出。所以说我有一个文本文件,在那个文本文件中有

“名字,3010321,姓氏,432 美元”</p>

我要做的基本上是编写一个新文件,将姓放在名字之后,并将奖金(432 美元)增加 10%。

这是我的代码:

fullNames = []
numberID = []
Bonus = []

with open(“data.txt”) as file:
     lines = file.readlines()

     for name in lines:
         firstName, numID, lastName, bonusAmount = name.split(“,”)

         fullNames.append(firstName)
         numberID.append(numID)

         lastName, bonusAmount = name.split(“,”)
         fullNames.append(lastName)
         Bonus.append(bonusAmount * 10)

如果可能的话,我是否可以使用正在阅读的文件中的组件来编写一个新文件?

标签: pythonfile-io

解决方案


Here's one way to do it. Note that I'm using a StringIO which is a file-like object, instead of reading from a local file. Also note that I'm splitting on , since this is the actual separator in the file (as there is a space after each comma).

from io import StringIO

string_value = StringIO("""\
firstName, 3010321, lastName, $432
Johnny, 1234567, Doe, $21\
""")

fullNames = []
numberID = []
Bonus = []
new_lines = []

lines = string_value.readlines()

for name in lines:
    firstName, numID, lastName, bonusAmount = name.split(", ")

    # Multiply it by 110%, which represents a 10% increase
    bonusAmount = float(bonusAmount.lstrip('$')) * 1.10

    fullNames.append((firstName, lastName))
    numberID.append(numID)
    Bonus.append(bonusAmount)

    line = f'{firstName}, {lastName}, {numID}, ${bonusAmount:.2f}'
    new_lines.append(line)

with open('out_file.txt', 'w') as out_file:
    out_file.write('\n'.join(new_lines))

Contents of out_file.txt:

firstName, lastName, 3010321, $475.20
Johnny, Doe, 1234567, $23.10

推荐阅读