首页 > 解决方案 > 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: ''      

标签: python-3.x

解决方案


我使我的程序正常工作,但奇怪的是没有从文件中删除特定行的功能。我将尝试自己制作一个并将其发布在这里,因为 https://stackoverflow.com/q/4710067/7987118中的所有答案都用于从文本文件中删除特定字符串。


推荐阅读