关于Python中的read(),readline(),readlines()与split()同时使用的问题

PECommunity 2008-09-23 08:33:00
在处理文件时发现了这样的现象:
1 用readline()读取文件,读到的行包含最后的'\n',split('-')时list最后一个元素末尾存在'\n' ; 一般情况下这不是我们期望的

2 用readlines()读取得到所有行的list以后,仍然存在以上情况;

3 用read() 读入所有然后split('\n')得到所有行的list后,就不会有'\n' ,这样也达到了我们的目的

问题:
python是处于何种需要才这样设计的? readline()还是可以理解的,readlines()既然得到的是所有行的list,为何还保留'\n'呢?

ps: 测试系统: linux-centos-python2.5
...全文
1915 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
iambic 2008-09-23
  • 打赏
  • 举报
回复
readline( [size])

Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line).3.7 If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. An empty string is returned only when EOF is encountered immediately. Note: Unlike stdio's fgets(), the returned string contains null characters ('\0') if they occurred in the input.

37,719

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧