Python新手。 使用此代码Python只打印第一行
#!/usr/bin/env python2
with open('/tmp/cadrootcomp1.firstwords',mode="rb") as f:
print '/'.join(f.read().split('/')[:2]) + '/'
获取输出: ABC/DEF/
当原线为ABC/DEF/GHI
所以这个工作得很好。需要此脚本在文件的其他行上运行。它只处理第一行。
Python新手。 使用此代码Python只打印第一行
#!/usr/bin/env python2
with open('/tmp/cadrootcomp1.firstwords',mode="rb") as f:
print '/'.join(f.read().split('/')[:2]) + '/'
获取输出: ABC/DEF/
当原线为ABC/DEF/GHI
所以这个工作得很好。需要此脚本在文件的其他行上运行。它只处理第一行。
您正在寻找这样的事情:
#!/usr/bin/env python2
with open('/tmp/cadrootcomp1.firstwords',mode="rb") as f:
for line in f:
print '/'.join(line.split('/')[:2]) + '/'
作品。谢谢! – Glad
不知道我理解正确的话你正在尝试做的。如果您尝试遍历文件中的行,请尝试此操作。
with open('/tmp/cadrootcomp1.firstwords',mode="rb") as lines: for line in lines: print '/'.join(line.split('/')[:2]) + '/'
作品。谢谢! – Glad
我觉得下面一个更好。我猜你正在使用切片file.read()
后删除\n
。一个更好的办法来做到这一点是使用strip()
这样的:
f.read().strip()
你甚至都不需要,阅读一行行的时候。
with open('/tmp/cadrootcomp1.firstwords',mode="rb") as f:
for line in f:
print line.rsplit('/',1)[0] + '/'
你需要使用一个循环读取所有行。 'f.read()'一次读取 –
新的Python一行。你能说明这个循环是如何工作的吗? – Glad