Python硬币翻转代码问题:如何删除.text文件中的行?



所以我想写一个基本的硬币翻转程序,我将在网络上实现,我需要三个.text文件:头部,皇冠和总计以保持总体值。是否有算法或模块可以让您删除文件的特权内容? (很抱歉我的问题有任何问题,这是我第一次在堆栈中提问(

我尝试运行代码,它可以工作。我的问题是,在它读取并尝试写入新数字后,新数字会在前一个数字之后写入。我在文件处理方面的唯一过期时间是在 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 用于从文本文件中删除特定字符串。

最新更新