How would I append the data I have extracted from a file using the current python code

Viewed 32

new to python here. I am trying to extract certain sections that has display bitcoin prices. I want to only show me the prices after reading the rest of the file contents. I'm stuck with this current code

sentences = []
words_count = 0
word = input("Enter word: ")
count  = 0
# file containing words and numbers
with open('data.txt') as file:
for line in file:
    words = line.split()
    words_count += len(words)
    sentences.append(line)
for line in sentences:
    if word in line:
        btc = (line[13:21])
        print(btc)
        count += 1
    else:
        count == 0
        print('Not found')
print(count, 'lines contain', word)
1 Answers

I don't know if I understand what you want to do but ...

  • you have wrong indentations,
  • you should check count == 0 after for-loop
  • if you want to print prices after line contain then you should keep them on list and use for-loop after line contain to display them
word = input("Enter word: ")

# --- read lines from file ---

sentences = []
words_count = 0

with open('data.txt') as file:
    for line in file:
        words = line.split()
        words_count += len(words)
        sentences.append(line)

# --- work with lines ---

count  = 0
prices = []

for line in sentences:
    if word in line:
        btc = line[13:21]
        #print(btc)
        prices.append(btc)
        count += 1
            
# - after loop -

if count == 0:
    print('Not found')
else:
    print(count, 'lines contain', word)
    for btc in prices:
        print(btc)

EDIT:

In this example you don't have to use count += 1 but after loop use count = len(prices)

Related