【发布时间】:2013-10-09 01:51:26
【问题描述】:
我的文件:
Offices 10
MedicalOffice 15
PostOffice 30
Mall 200
如何让 python 只读取第二列。 喜欢得到:
10
15
30
200
我已经尝试过可能的方法来让它只读取 10、15、30 等...而不是名称。我试过这个没有名字,它工作正常。但我需要在文本文件中包含名称。有什么帮助吗?谢谢
def something(file1):
with file1 as f:
nums = [int(line) for line in f]
print("Read from File: ", nums)
textFileName = input("Enter the filename: ")
file1 = open(textFileName)
something(file1)
谢谢。
【问题讨论】:
-
这是第二个列。第二个行是
MedicalOffice 15。 -
@abarnert 很好。我的错字。感谢您的提醒!
-
是的,我认为这只是一个错字,但最好是修正它而不是让未来的读者感到困惑……
-
同时,您可能不想在顶层执行
open,在函数内部执行with。只要您在这种情况下只调用something,这基本上可以工作,但这很奇怪。通常,您希望open直接在with语句中。with open(textFileName) as file1: something(file1)和something没有with,或者只有something(textFileName)和something内部,它在with中打开文件。 (这很难在评论中解释;希望你明白吗?)