Python将文件读入列表 - 编辑

时间:2016-05-03 11:13:39

标签: python

  • 编辑 - 似乎我在测试部件数量时出错:

    lines = len(file.readlines()) N = lines - 2

当我在一个单独的脚本中测试它时它确实有效......

初学者需要帮助。我的python脚本有问题,我自己无法解决。该脚本应该从文本文件中读取浮点并进行一些计算。我无法将数字放入列表R[]

下面是文本文件的示例,其中第一行(s[0])是标称值,第二行(s[1])是容差,以下行是一些电阻。

3300.0

10.0

3132.0

3348.5

3557.3

3467.4

3212.0

3084.6

3324.0

我有以下代码:

R = []
Ntoolow = Nlow = Nhigh = Ntoohigh = 0.0
lines = 0

def find_mean(q):
    tot = 0.0
    c = len(q)
    for x in range (c):
        tot += q[x]
        return tot/c


def find_median(q):
    c = len(q)
    if c%2:
        return float(q[int(c/2)])
    else:
        c /= 2
        return (q[int(c)]+q[int(c-1)])/2.0


file_name = input("Please enter the file name: ")
file = open(file_name, "r")

s = file.readlines()

Rnom = float(s[0])
Tol = float(s[1])


keepgoing = True

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


lines = len(file.readlines())
N = lines - 2
R.sort()


Rmin = R[0]
Rmax = R[N-1]

Rlowerlimit = Rnom - Tol
Rupperlimit = Rnom + Tol


for rn in R:
    if rn < Rlowerlimit:
        Ntoolow += 1
    elif rn < Rnom:
        Nlow += 1
    elif rn <= Rupperlimit:
        Nhigh += 1
    else:
        Ntoohigh += 1


Ptoolow = 100.0 * Ntoolow / N
Plow = 100.0 * Nlow / N
Phigh = 100.0 * Nhigh / N
Ptoohigh = 100.0 * Ntoohigh / N


Rmean = find_mean(R)
Rmedian = find_median(R)


print("Total number of parts tested: " + str(N))
print("The largest resistor is: " + str(Rmax) + " and the smallest is: " + str(Rmin))
print("The mean is: " + str(Rmean) + " and the median is: " + str(Rmedian))
print("The percentage of resistors that have too low tolerance is: " + str(Ptoolow) + "%")
print("The percentage of resistors that have low tolerance is: " + str(Plow) + "%")
print("The percentage of resistors that have high tolerance is: " + str(Phigh) + "%")
print("The percentage of resistors that have too high tolerance is: " + str(Ptoohigh) + "%")

file.close()

4 个答案:

答案 0 :(得分:1)

Python有许多库可以从CSV文件中读取信息,例如csv,numpy和pandas。请尝试以下方法:

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

然后你可以迭代这样的行:

for row in reader:
    print(row)

答案 1 :(得分:1)

略过空行,并使用rstrip()删除换行符\n

filename = 'test.dat'

with open(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]

答案 2 :(得分:0)

没有必要重新发明轮子,Python知道当它到达文件的末尾时,你不需要添加你自己的子句(加上,不会检测到“”可能在空行结束?不是肯定)。

试试这段代码:

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

答案 3 :(得分:0)

替换您的代码,

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

with,

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

它给了我答案......

以下是我编辑代码后的输出

Total number of parts tested: -2
The largest resistor is: 3348.5 and the smallest is: 10.0
The mean is: 1.11111111111 and the median is: 3300.0
The 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%