文件中的文本未打印

2024-06-17 12:42:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我想打印文件中的文本,但输出没有显示任何内容

def viewstock():
 replit.clear()
 print ("Here is the current stock\n-------------------------")
 f = open("stock", "a+")
 p = f.read()
 print (p)
 print ("Press enter to return to the stock screen")
 e = input ('')
 if e == '':
   stock_screen()
 else:
   stock_screen()

有人知道怎么解决这个问题吗


Tags: theto文本内容hereisdefstock
3条回答

如果要读取文件,请在读取模式下打开它,而不是附加模式。当您在附加模式下打开它时,文件的位置在末尾,它不返回任何内容

试试这个:

def viewstock():
 replit.clear()
 print ("Here is the current stock\n            -")
 f = open("stock", "r")
 p = f.read()
 print (p)
 print ("Press enter to return to the stock screen")
 e = input ('')
 if e == '':
   stock_screen()
 else:
   stock_screen()

要读取文件并打印,您可能只需要在读取模式下打开文件

def viewstock():
    replit.clear()
    print ("Here is the current stock\n            -")
    with open("stock", "r") as f:
        p = f.readlines()
        print (p)
    print ("Press enter to return to the stock screen")

    e = input ('')
    stock_screen()     #You just need to call it once

    #this entire section can be ignored and instead the above line will do
    '''
    The if and else does the same thing. So no need to use if statement
    if e == '':
        stock_screen()
    else:         
        stock_screen()
    '''

您可以只在read模式下打开文件,而不在append模式下打开。请尝试以下代码:

f = open('stock', 'r') -> #(r stands for read mode)
file_contents = f.read()
print (file_contents)
f.close()

相关问题 更多 >