首页 > 解决方案 > 从文本文件创建的列表中删除添加的“\n”部分

问题描述

我从文本文件中读取行以获取路径列表,txt 文件示例为:

/data0/home/rslat/GFDL/archive/edg/fms/river_routes_gt74Sto61S=river_destination_field ,
/data0/home/rslat/GFDL/archive/fms/mom4/mom4p1/mom4p1a/mom4_ecosystem/preprocessing/rho0_profile.nc ,
/data0/home/rslat/GFDL/archive/fms/mom4/mom4p0/mom4p0c/mom4_test8/preprocessing/fe_dep_ginoux_gregg_om3_bc.nc=Soluble_Fe_Flux_PI.nc ,
/data0/home/rslat/GFDL/archive/jwd/regression_data/esm2.1/input/cover_type_1860_g_ens=cover_type_field ,

要阅读它,我正在使用:

x = open('/File_list.txt', 'r')
y = [line.split(',') for line in x.readlines()]

但是每个元素现在\n都在末尾,例如y[2]

['/data0/home/rslat/GFDL/archive/fms/mom4/mom4p0/mom4p0c/mom4_test8/preprocessing/fe_dep_ginoux_gregg_om3_bc.nc=Soluble_Fe_Flux_PI.nc ',
 '\n']

我如何删除这些不必要的\n?试过:

good = [line.rstrip('\n') for line in y]

但是得到了错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-33-d3ed0e6bdc26> in <module>
----> 1 good = [line.rstrip('\n') for line in y]

<ipython-input-33-d3ed0e6bdc26> in <listcomp>(.0)
----> 1 good = [line.rstrip('\n') for line in y]

AttributeError: 'list' object has no attribute 'rstrip'

似乎是一个简单的问题,但我还不能解决它。​</p>

标签: pythonlist

解决方案


这应该会有所帮助。您可以使用检查该行是否为空if line.strip()

前任:

with open('/File_list.txt') as infile:
    #good = [line.strip().split(",") for line in infile if line.strip()]
    good = [line.strip(" ,\n") for line in infile if line.strip()]

推荐阅读