简体   繁体   English

从文件中读取行添加附加行

[英]Reading line from a file adding additional line

This is the contents of my file ITEM.dat is这是我的文件 ITEM.dat 的内容

DB1:TEST1:Y DB1:TEST1:Y

DB2:TEST2:N DB2:TEST2:N

Code is代码是

MYFILE='/tmp/ITEM.dat'
M_ITMES=['TEST1'] 
for ITEM in ITMES:
if ITEM in open(MYFILE):
    if not line.startswith('#'):
        ITEM_YN=(line.split(':'))[2]
        print(ITEM_YN)

The print command results in additional blank line after Y打印命令会在 Y 之后产生额外的空行

Y

This does not occur when I use当我使用时不会发生这种情况

ITEM_YN=(line.split(':'))[1]

line includes the new line character as does the final item in line.split(':') . line包括换行符,就像line.split(':')中的最后一项line.split(':') Since you likely want to use that item for other things, trim the newline before the split:由于您可能想将该项目用于其他用途,请在拆分之前修剪换行符:

ITEM_YN = line.strip().split(':')[2]

Notice, I also got rid of those extra unneeded parens.注意,我还去掉了那些多余的不需要的括号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM