python读取用户输入文件_如何在Python中读取输入文件?

尽管在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()

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值