Skip to content Skip to sidebar Skip to footer

Python Read File Into List - Edit

edit - It seems that I have made an error with the calculation of number of parts tested: lines = len(file.readlines()) N = lines - 2 It did work when i tested it in a separate s

Solution 1:

Python has a number of libraries that can read information from CSV files, such as csv, numpy and pandas. Try the following:

import csv
withopen('filename.csv','r') as f:
    reader = csv.reader(f)

You can then iterate over the rows like this:

forrowin reader:
    print(row)

Solution 2:

Skip the empty lines and remove line breaks \n with rstrip():

filename = 'test.dat'withopen(filename, 'r') as f: 
    s = [float(line.rstrip()) for line in f if line.rstrip()]

print(s)
#[3300.0, 10.0, 3132.0, 3348.5, 3557.3, 3467.4, 3212.0, 3084.6, 3324.0]

Solution 3:

Replace your code ,

while keepgoing:
     s = file.readline()
     ifs== "":
         keepgoing = False
     else:
         R.append(float(s))

with,

for i in s:
    R.append(float(i))

Its giving me the answer...

Here is the output after I Edited your code,

Total number of parts tested:-2The largest resistor is: 3348.5 and the smallest is:10.0The mean is: 1.11111111111 and the median is:3300.0The percentage of resistors that have too low tolerance is:-200.0%The percentage of resistors that have low tolerance is:-0.0%The percentage of resistors that have high tolerance is:-50.0%The percentage of resistors that have too high tolerance is:-200.0%

Solution 4:

There's no need to reinvent the wheel, Python knows when it's reached the end of a file, you don't need to add your own clause (plus, won't detecting for "" possibly end on empty lines? Not too sure).

Try this code:

withopen(file_name) as f:
   try: 
       R = float(f.readlines())
   except TypeError:
       pass

Post a Comment for "Python Read File Into List - Edit"