简体   繁体   English

Python 文件写入 txt 文档,但读取时擦除

[英]Python file writes to txt document but erases on read

Hello I am developing this program to use an api to get opening and closing prices of certain stocks that the user enters.您好,我正在开发此程序以使用 api 来获取用户输入的某些股票的开盘价和收盘价。 I am making the gui portion of the program using PySimpleGui.我正在使用 PySimpleGui 制作程序的 gui 部分。 I have many text fields where the user enters the ticker symbol.我有很多文本字段,用户可以在其中输入股票代码。 I then save that to a list called tickerList .然后我将其保存到名为tickerList的列表中。 I then write this list to storedTickers.txt .然后我将此列表写入storedTickers.txt I then created, in another file called readTickers.py the funcion openTickerList() .然后我在另一个名为readTickers.py的文件中创建了函数openTickerList() In theory I wanted the user to enter the tickers then they could close the program and when they reopened it tickerList would be equal to openTickerList()理论上我希望用户输入代码然后他们可以关闭程序,当他们重新打开它时, tickerList将等于openTickerList()

I do come into some problems though, when I put ticker symbols in the text fields and hit "done" it saves them to the text file but if I open the program again and just click "x" it erases the txt file.我确实遇到了一些问题,当我在文本字段中输入股票代码并点击“完成”时,它会将它们保存到文本文件中,但是如果我再次打开程序并单击“x”,它会删除 txt 文件。 It shouldnt though because the list should only update if I click Done (I set an if statement event handler).它不应该,因为只有当我单击Done时列表才应该更新(我设置了一个 if 语句事件处理程序)。 The reason I need the person to be able to open the program and close it without entering new tickers is they need to click the button Get Stock Info (which will used the saved tickers and then get the stock info from the api)我需要该人能够在不输入新代码的情况下打开程序并关闭它的原因是他们需要单击按钮Get Stock Info (它将使用保存的代码,然后从 api 获取股票信息)

Here is the code for gui.py这是gui.py的代码

import PySimpleGUI as sg
import pickle
global tickerList
global keyNames
global fileName
global openFile
global tryList
from readTickers import openTickerList


openFile = open('storedTickers.txt', 'w')
#tickerList = pickle.load(openFile)
tickerList = openTickerList() #this should get the tickers from the last time the person entered them 

def eraseFile():
    openFile.truncate(0)

keyNames = ['first entry', 'second entry', 'third entry', 'fourth entry', 'fifth entry', 'sixth entry', 'seventh entry', 'eighth entry', 
    'ninth entry', 'tenth entry', 'eleventh entry', 'twelfth entry', 'thirteenth entry', 'fourteenth entry', 'fifteenth entry',
    'sixteenth entry', 'seventeenth entry', 'eighteenth entry', 'nineteenth entry', 'twentieth entry']
sg.theme('Dark')
layout = [
    [sg.Button('Done')],
    [sg.Button('Reset All Tickers')],
    [sg.Button('Get Stock Info')],
    [sg.Text('1:'), sg.InputText(key='first entry'), sg.Text('11:'), sg.InputText(key='eleventh entry')],
    [sg.Text('2:'), sg.InputText(key='second entry'), sg.Text('12:'), sg.InputText(key='twelfth entry')],
    [sg.Text('3:'), sg.InputText(key='third entry'), sg.Text('13:'), sg.InputText(key='thirteenth entry')],
    [sg.Text('4:'), sg.InputText(key='fourth entry'), sg.Text('14:'), sg.InputText(key='fourteenth entry')],
    [sg.Text('5:'), sg.InputText(key='fifth entry'), sg.Text('15:'), sg.InputText(key='fifteenth entry')],
    [sg.Text('6:'), sg.InputText(key='sixth entry'), sg.Text('16:'), sg.InputText(key='sixteenth entry')],
    [sg.Text('7:'), sg.InputText(key='seventh entry'), sg.Text('17:'), sg.InputText(key='seventeenth entry')],
    [sg.Text('8:'), sg.InputText(key='eighth entry'), sg.Text('18:'), sg.InputText(key='eighteenth entry')],
    [sg.Text('9:'), sg.InputText(key='ninth entry'), sg.Text('19:'), sg.InputText(key='nineteenth entry')],
    [sg.Text('10:'), sg.InputText(key='tenth entry'), sg.Text('20:'), sg.InputText(key='twentieth entry')],

]
window = sg.Window("Stock Market Price Grabber", layout)

while True:
    event, values = window.read()
    if event in (None, 'Cancel'):
        break
    if event == 'Done':
        for x in range(20):
            tickerList.append(values[keyNames[x]] + '\n')
        for elements in tickerList:
            if len(tickerList[x]) < 0:
                tickerList.remove(tickerList[x])
        openFile.writelines(tickerList) 
    if event == 'Reset All Tickers':
        eraseFile()
print(tickerList)
window.close()

Here is the code for readTickers.py这是readTickers.py的代码

def openTickerList():
    openFile2 = open('storedTickers.txt', 'r')
    result = openFile2.readlines()
    return result
    #print(result)

This line:这一行:

openFile = open('storedTickers.txt', 'w')

will clobber the contents of storedTickers.txt every time it runs.每次运行时都会破坏storedTickers.txt的内容。 If you'd like the data to be intact for the next run a refactoring is needed, or replace the 'w' with 'r+' , which will open the file for read + write without nuking your data.如果您希望数据在下次运行时保持完整,则需要进行重构,或者将'w'替换为'r+' ,这将打开文件以进行读取和写入,而不会破坏您的数据。

Here the writable file object isn't needed until the Done event or erase() , so the open(..., 'w') could be deferred until needed for those functions.此处可写文件 object 直到Done事件或erase()才需要,因此open(..., 'w')可以推迟到这些功能需要时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM