python - 如何在使用文件中的组件时覆盖文件?
问题描述
我无法获得我想要的输出。我不确定如何解决这个问题,因为每次我运行代码时都没有得到任何输出。所以说我有一个文本文件,在那个文本文件中有
“名字,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)
如果可能的话,我是否可以使用正在阅读的文件中的组件来编写一个新文件?
解决方案
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
推荐阅读
- android - 为 AOSP 应用程序去混淆 proguard
- javascript - 我如何使用 Promise 来获取 SQLite 数据库事务的结果?
- python - PyCharm 错误 - 没有名为“sip”的模块(PyQt4)
- typescript - 如何在 VS Code 中以编程方式关闭特定文件
- angular - 自定义 Angular 管道根据应用程序的语言环境显示日期
- c++ - 这可以到达函数的末尾并且不返回任何内容吗?
- multithreading - Perl:带有 Coro 和 AnyEvent 的多线程服务器
- go - 如何获取 URL 的最后一个路径段
- oracle - 如何编写块以跳过失败过程
- c++ - 我可以更改 CPU 模式以读取内存吗?