Skip to content
Advertisement

opening txt file and creating lists from the txt file

file = open('covid.txt', 'rt')
everything = file.read()
list = file.read()
i = [row.rstrip('n') for row in everything]
print(i)
    covid = []
    counter = 0
    for number in line.split(" "):
        file.append(number)
    for x in range(4):
        print(x)

file.close()

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 ?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement