python - 从文本文件创建的列表中删除添加的“\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>
解决方案
这应该会有所帮助。您可以使用检查该行是否为空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()]
推荐阅读
- javascript - 如何使用正则表达式创建一个新的 json,它是使用 javascript 的其他 json 的子集?
- java - 为什么我的 IDEA 会报这个错误——“无法解析符号‘synchronizedList’”
- c# - GridFS 中的 C# MongoDB 驱动程序下载文件
- c# - 如何在 ProgressRing 中设置为 true
- java - 将数据添加到“价格”和“数量”列单元格时更新 JTable 中的“金额”列单元格
- opengl - 使用 for 循环绘制球体
- java - 将 DATETIME 从 SQLite 解析为 java.SQL.Timestamp 时出错
- android - 当我离开我的应用程序时如何停止 MediaPlayer,但当我移动到另一个 Activity (Android Studio) 时不能
- python - 使用范围遍历列表
- ios - 带参数的本地化字符串在参数周围添加换行符和括号