[英]Why won't this function append values from the textfile to my list?
def read1(file): #this function will read and extract the first column of values from the
with open(file,"r") as b: # text allowing us to access it later in our main function
list1 = list(b)
lines = b.readlines()
result1 = []
for i in lines:
result1.append(list1.split()[0])
b.close
return result1
x = read1("XRD_example1.txt")
Any errors clearly visible?任何错误清晰可见?
You do:你做:
list1 = list(b)
lines = b.readlines()
but the first of those lines already reads up all contents of your file, there's nothing to be read in the second line.但是这些行中的第一行已经读取了文件的所有内容,第二行中没有任何内容可读取。
def read1(file): #this function will read and extract the first column of values from the
with open(file,"r") as b: # text allowing us to access it later in our main function
lines = b.readlines()
result1 = []
for i in lines:
result1.append(i.split()[0])
# no need for close, when using 'with open()'
return result1
should work, or even better:应该工作,甚至更好:
def read1(file):
with open(file,"r") as b:
return [i.split()[0] for i in b.readlines()]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.