简体   繁体   中英

Python: Checking and adding to a text file

I've been working on this, and googling for hours. I can't seem to figure out what is going wrong.

The purpose of this program, is to check a text file for stock market ticker symbols, and add a ticker only if it is not already in the file.

There are two things going wrong. When the text file is empty, it won't add any tickers at all. When it has even a single character in the text file, it is adding every ticker you give it, regardless of if that ticker is already on the list.

import re

def tickerWrite(tick):
    readTicker = open('Tickers.txt', 'r')
    holder = readTicker.readlines()
    readTicker.close()

    if check(tick) == False:
        writeTicker = open('Tickers.txt', 'w')
        holder.append(tick.upper() + '\n')
        writeTicker.writelines(holder)
        writeTicker.close()

def check(ticker):
    with open('Tickers.txt') as tList:
        for line in tList:
            if re.search(ticker, line):
                return True
            else:
                return False

Another module calls AddReadTickers.tickerWrite(ticker) in order to add tickers entered by a user.

First of all.

I suggest to use

if not check(tick):

instead of

if check(tick) == False:

Then. I think it is better to use

writeTicker = open('Tickers.txt', 'a')

and you will not need holder at all.

Just tried to rewrite the code

from __future__ import print_function

import re
import sys


def tickerWrite(tick):
    if not check(tick):
        with open('Tickers.txt', 'a') as writeTicker:
            print(tick.upper(), file=writeTicker)

def check(ticker):
    with open('Tickers.txt') as tList:
        for line in tList:
            return bool(re.search(ticker, line))

if __name__ == '__main__':
    tickerWrite(sys.argv[1])

It works as it seems for me.

  1. function check should return False defaultly. It returns None for an empty Tickers.txt, that causes the line "if check(tick) == False:" always False. This is the reason it won't add any ticker for empty file
  2. my guess is because of content of ticker. Since you use the ticker as pattern, it probably cause unexpected result when ticker contains some special characters of regular expression. In my understanding, you can just use code

if ticker==line:
    return True
else:
    return False

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