Home > other >  opening txt file and creating lists from the txt file
opening txt file and creating lists from the txt file

Time:04-20

enter image description here

I'm trying to Read the file "covid.txt" into two lists. The first list should contain all the "day" values from the file. The second list should contain all the "new cases" values.

my list in column

0 188714

1 285878

2 1044839

3 812112

4 662511

5 834945

6 869684

7 397661

8 484949

I needed to be this way

x = [ 0, 1 , 2, 3,...]

y = [188714, 285878, 1044839, 812112, ...]

I have tried so many different things I'm new to Python and trying to figure out how to start this. anyone can lead me to the right direction ?

CodePudding user response:

Assuming your data file has all of those numbers in one long line, this should work:

# Read the words from the file.  This is a list, one word per entry.
words = open('covid.txt','rt').read().split()
# Convert them to integers.
words = [int(i) for i in words]
# Divide into two lists by taking every other number.
x = words[0::2]
y = words[1::2]
print(x)
print(y)

Followup

Given this data:

0 188714
1 285878
2 1044839
3 812112
4 662511
5 834945
6 869684
7 397661
8 48494

My code produces this result:

[0, 1, 2, 3, 4, 5, 6, 7, 8]
[188714, 285878, 1044839, 812112, 662511, 834945, 869684, 397661, 48494]

which is exactly what you said you wanted.

CodePudding user response:

with open('covid.txt','rt') as f:
    all_lines = [line.split(' ') for line in f]
x, y = zip(*all_lines)

x and y will be tuples though. You can cast by list(x)

  • Related