在python中读取文件并返回字符串
我的目标是读入一个文件,并返回用户要求的相应信息。例如,我的文本文件如下所示(它表示该年以及该年的学生身高): 2013年 5.5.6.3 4.0 5.2 5.1 2014年 4.6 4.8 5.3 5.6 6.0 2015年 3.8 4.9 6.0 5.8 5.7 基本上,如果我进入2013年,我希望它返回对应于该年的高度列表(下面的行)。但我无法让它打印回字符串列表。帮点忙就好了在python中读取文件并返回字符串,python,string,while-loop,split,text-files,Python,String,While Loop,Split,Text Files,我的目标是读入一个文件,并返回用户要求的相应信息。例如,我的文本文件如下所示(它表示该年以及该年的学生身高): 2013年 5.5.6.3 4.0 5.2 5.1 2014年 4.6 4.8 5.3 5.6 6.0 2015年 3.8 4.9 6.0 5.8 5.7 基本上,如果我进入2013年,我希望它返回对应于该年的高度列表(下面的行)。但我无法让它打印回字符串列表。帮点忙就好了 #read in text file f = open("students.txt") #a
#read in text file
f = open("students.txt")
#ask for student year
year = input("Enter the year for the data you want to receive:")
#check to see if year is avialble
line = f.readline()
while True:
line = f.readline().split()
if line:
if line == year:
print(line)
else:
break
print("No data")
如果执行
f.readline().split()
,则会得到一个列表。因此,对于第一行,您将有类似于line=['2013']
的内容。另一方面,年份是一根弦。因此,如果用户输入2013
,类型(年份)=
,而类型(行)=
。因为它们永远不相等,所以if子句永远不True
,并且该行永远不会被打印出来
#read in text file
f = open("students.txt")
#ask for student year
year = input("Enter the year for the data you want to receive:")
#check to see if year is available
for line in f.readlines():
if year in line:
f.readline()
print ( f.readline() )
break
我想,如果有一个身高超过2000的学生,上面的代码就不起作用了。相反,试着把所有条目都读入字典。那么按年查询就很简单了
def readentries(f):
# read until we get `StopException` i.e. end of file
while True:
try:
# take two lines from the file and strip newlines
# and split heights by spaces to give a list of heights
yield next(f).strip(), next(f).strip().split()
except StopIteration:
# break out of the infinite while loop
break
with open('heights.txt') as f:
entries = dict(readentries(f))
year = input("Enter the year for the data you want to receive: ")
# query dict for supplied entry
if year in entries:
print('for year %s we have heights %s ' % (year, ', '.join(entries[year])))
else:
print('no data')
您可能需要将高度转换为
float
变量。这很容易添加。一种简单的方法是将文件的所有行读取到列表中,然后根据您想要的年份在该列表中查找索引,然后获取下一行
with open('students.txt', 'r') as f:
data = [i.strip() for i in f] # strip trailing space
year = input("Enter year: ")
try:
# find index, get the next line
line = data[data.index(year) + 1]
# split on whitespace, apply float()
item_list = [float(i) for i in line.split()]
except ValueError: # raised if year not found
print("No relevant data")
在与所需年份相等的行后打印下一行而不是空行
year = "2013"
with open("students.txt") as f:
stop = False
for line in f:
line = line.rstrip("\n")
if line == year:
stop = True
else:
if line and stop:
print line.split()
break
if not stop:
print "No data for year {}.".format(year)
您还可以构建两个列表,并通过迭代文件的行来构建字典:
with open("grade.txt", "r") as file:
year = []
height = []
for i in file:
if len(i.strip("\n")) == 4:
year.append(i.strip("\n"))
elif i != "\n":
height.append(i.strip("\n").split(" "))
ydict = {year[i]: height[i] for i in range(len(year))}
print(ydict['2013'])
由于数据包含一些空白行和制表符,因此您需要首先清理这些数据。然后,只需将偶数行(年份)添加为字典中的键(从零开始),将奇数行(高度)添加为字典中的值
year = input("Enter the year for the data you want to receive:")
with open("students.txt") as f:
# read stripped file lines into list keeping only those that contain data
data = [line.strip() for line in f.readlines() if line.strip() != '']
# build a dict from the data using list slicing to get the years (keys) and heights (values)
data_dict = dict(zip(data[0::2], data[1::2]))
# print the heights if the year exists otherwise 'No data.'
print(data_dict.get(str(year)) if data_dict.get(str(year)) else 'No data.')