为什么此函数不将文本文件中的值附加到我的列表中?
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")
是否有清晰可见的错误?
你做到了:
list1 = list(b)
lines = b.readlines()
但是这些行中的第一行已经读完了文件的所有内容,第二行没有任何内容可读。
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
应该可以,甚至更好:
def read1(file):
with open(file,"r") as b:
return [i.split()[0] for i in b.readlines()]
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")
是否有清晰可见的错误?
你做到了:
list1 = list(b)
lines = b.readlines()
但是这些行中的第一行已经读完了文件的所有内容,第二行没有任何内容可读。
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
应该可以,甚至更好:
def read1(file):
with open(file,"r") as b:
return [i.split()[0] for i in b.readlines()]