简体   繁体   中英

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. I am making the gui portion of the program using PySimpleGui. I have many text fields where the user enters the ticker symbol. I then save that to a list called tickerList . I then write this list to storedTickers.txt . I then created, in another file called readTickers.py the funcion 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()

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. It shouldnt though because the list should only update if I click Done (I set an if statement event handler). 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)

Here is the code for 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

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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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