尽管在Python中,您总会发现各种简洁的技巧和时间节省器(实际上,实际项目中推荐的一个时间节省器是with语句),但我建议,在您真正熟悉文件I/O之前,您应该坚持如下做法:infile = open("input.txt", "r") # the "r" is not mandatory, but it tells Python you're going to be reading from the file and not writing
numCases = int(infile.readline())
infile.readline() #you had that blank line that doesn't seem to do anything
for caseNum in range(numCases):
# I'm not sure what the lines in the file mean, but assuming each line is a separate case and is a bunch of space-separated strings:
data = infile.readline().split(" ")
# You can also use data = list(map(int, infile.readline.split(" "))) if you're reading a bunch of ints, or replace int with float for a sequence of floats, etc.
# do your fancy algorithm or calculations on this line in the rest of this for loop's body
infile.close() # in the case of just reading a file, not mandatory but frees memory and is good practice
也可以选择这样做(如果你没有阅读大量的数据,这完全取决于你自己的喜好):infile = open("input.txt", "r")
lines = infile.read().strip().split("\n") # the .strip() eliminates blank lines at beginning or end of file, but watch out if a line is supposed to begin or end with whitespace like a tab or space
# There was the (now-redundant) line telling you how many cases there were, and the blank following it
lines = lines[2:]
for line in lines:
# do your stuff here
infile.close()