python-3.x - Python coinflip 代码问题:如何删除 .text 文件中的行?
问题描述
因此,我正在尝试编写一个基本的硬币翻转程序,我将在网络中实现我需要三个 .text 文件:heads、crowns 和 total 以保持总体价值。是否有算法或模块可以让您删除文件的 privius 内容?(抱歉我的问题有任何问题,这是我第一次在堆栈中提问)
我尝试运行代码并且它有效。我的问题是,在它读取并尝试写入新号码之后,新号码会在前一个号码之后写入。我对文件处理的唯一经验是在 c 和 c 中,如果你编写它会创建一个新文件。
def main():
tot_num = open('total.txt', 'r+')
while True:
try:
x = input('Flip(F) or Exit(E)').lower()
except ValueError:
print('You had ur options try again')
else:
if x == 'f' or x == 'flip':
cf = coin_flip()
if cf == 'head':
print('Coin --> HEAD')
heads = open('heads.txt', 'r+')
h_num = int(heads.read())
heads.write(f'{h_num + 1}')
tn = int(tot_num.read())
tot_num.write(f'{tn + 1}')
heads.close()
show_coin_flip_num()
elif cf == 'crown':
print('Coin --> CROWN')
crowns = open('crown.txt', 'r+')
c_num = int(crowns.read())
crowns.write(f'{c_num + 1}')
tn = int(tot_num.read())
tot_num.write(f'{tn + 1}')
crowns.close()
show_coin_flip_num()
else:
break
else:
print('Exiting...')
break
错误基本上就在那里,因为添加新号码后它会在前一个号码旁边,下次可以正常读取。它从文件中获取“012”。
Traceback (most recent call last):
File "file_path", line 462, in <module>
main()
File "file_path", line 442, in main
tn = int(tot_num.read())
ValueError: invalid literal for int() with base 10: ''
解决方案
我使我的程序正常工作,但奇怪的是没有从文件中删除特定行的功能。我将尝试自己制作一个并将其发布在这里,因为 https://stackoverflow.com/q/4710067/7987118中的所有答案都用于从文本文件中删除特定字符串。
推荐阅读
- java - 反转单词而不改变大写或标点符号
- docker - 在 GCP 上构建 docker 映像时进程被杀死
- r - (R, purrr) 按名称对列对进行迭代,一个常量和一个来自列表
- python-3.x - pandas read_excel MultiIndex 表中的行为不一致
- javascript - Jquery - 预先选择复选框时禁用复选框
- apache-kafka - Kafka - 顺序 I/O
- cloud-foundry - 找不到“/cloudfoundryapplication”目录
- sql - 按模式排列的雪花子串
- amazon-web-services - AWS API 请求标头中的 Content-Type 为小写
- c# - 如何在 Unity 中剔除不在 2D 相机视图中的预制件