V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
onlinezu
V2EX  ›  Python

Python 读写文件时如何实现换行?

  •  
  •   onlinezu · 2015-05-03 21:27:22 +08:00 · 5543 次点击
    这是一个创建于 3277 天前的主题,其中的信息可能已经有所发展或是发生改变。
    with open(r'E:\test.txt', 'a+') as f:
    f.write(str(a))
    9 条回复    2015-05-05 00:38:09 +08:00
    messense
        1
    messense  
       2015-05-03 21:31:58 +08:00   ❤️ 3
    with open(r'E:\test.txt', 'a+') as f:
    ----f.write(str(a) + os.linesep)
    kevinyoung
        2
    kevinyoung  
       2015-05-03 21:52:12 +08:00
    "\n"?
    goodryb
        3
    goodryb  
       2015-05-03 21:57:18 +08:00   ❤️ 1
    看你是什么系统了,如果代码自动兼容的话,看1楼的
    如果目标系统很明确,可以直接写代码里面
    *nux “\n”
    Windows “\r\n“
    onlinezu
        4
    onlinezu  
    OP
       2015-05-03 22:10:36 +08:00
    我的是windows,为什么我搜到 http://stackoverflow.com/questions/21636213/why-you-shouldnt-use-os-linesep-when-editing-on-text-mode ,如果写成 f.write(str(word) + \r\n),提示SyntaxError: unexpected character after line continuation character 弄了一个晚上了
    Delbert
        5
    Delbert  
       2015-05-03 22:12:58 +08:00   ❤️ 1
    @onlinezu f.write(str(word) + '\r\n')
    字符串加引号谢谢。
    v2014
        6
    v2014  
       2015-05-03 22:53:56 +08:00
    ohyeah521
        7
    ohyeah521  
       2015-05-04 08:18:48 +08:00
    os.linesep 是最好的选择
    onlyice
        8
    onlyice  
       2015-05-04 09:35:19 +08:00
    看情况决定使用 os.linesep 还是一律 \n
    如果你生成的文件需要交给 *nix 环境去读取,建议使用 \n
    onlinezu
        9
    onlinezu  
    OP
       2015-05-05 00:38:09 +08:00
    不知道哪里出错了,请大家指出,到最后没有输出全部,只能得到 a

    result1 = [1,"2", "a"]
    for item in result1:
    print(item)
    with open(r'E:\tools\fenci1.txt', 'a+') as file:
    file.write("\r\n")
    file.write(str(item) + "\r\n")
    file.write("".join(str(item)) + os.linesep)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4157 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 05:29 · PVG 13:29 · LAX 22:29 · JFK 01:29
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.