我有一个包含以下信息的文本文件:
SHRO
BJRD
ZNJK
GRMI
我想以一种可以逐行加载它们的方式保存它们。我的意思是,假设它的名字是“name”,我想要第4列如下:
name[3] = "GRMI"
我该怎么做?
答案 0 :(得分:3)
你可以这样做:
with open('filename.txt') as f:
name = f.read().split()
EDIT
根据您发布的答案,我知道您只需要在一行中打印名称,因此修改后的代码将是:
with open('filename.txt') as f:
print f.read().split('\n')[12][:4] # Assuming that all of the those consist of 4 characters.
# That number 12 was just an example.
否则,
with open('filename.txt') as f:
names = f.read().split('\n')
print names[12].split()[0] # Again, that number is an example.
答案 1 :(得分:0)
你可能想要像
这样的东西with open('stationlist', 'r') as f:
station_names = [line.split()[0] for line in f]
如果所有电台名称都是四个字符,则列表推导可以替换为
[line[:4] for line in f]