推荐学习书目
› 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 · May 3, 2015 · 6662 views
    This topic created in 4175 days ago, the information mentioned may be changed or developed.
    with open(r'E:\test.txt', 'a+') as f:
    f.write(str(a))
    9 replies  •  2015-05-05 00:38:09 +08:00
    messense
        1
    messense  
       May 3, 2015   ❤️ 3
    with open(r'E:\test.txt', 'a+') as f:
    ----f.write(str(a) + os.linesep)
    kevinyoung
        2
    kevinyoung  
       May 3, 2015
    "\n"?
    goodryb
        3
    goodryb  
       May 3, 2015   ❤️ 1
    看你是什么系统了,如果代码自动兼容的话,看1楼的
    如果目标系统很明确,可以直接写代码里面
    *nux “\n”
    Windows “\r\n“
    onlinezu
        4
    onlinezu  
    OP
       May 3, 2015
    我的是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  
       May 3, 2015   ❤️ 1
    @onlinezu f.write(str(word) + '\r\n')
    字符串加引号谢谢。
    ohyeah521
        7
    ohyeah521  
       May 4, 2015
    os.linesep 是最好的选择
    onlyice
        8
    onlyice  
       May 4, 2015
    看情况决定使用 os.linesep 还是一律 \n
    如果你生成的文件需要交给 *nix 环境去读取,建议使用 \n
    onlinezu
        9
    onlinezu  
    OP
       May 5, 2015
    不知道哪里出错了,请大家指出,到最后没有输出全部,只能得到 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)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5759 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 48ms · UTC 08:26 · PVG 16:26 · LAX 01:26 · JFK 04:26
    ♥ Do have faith in what you're doing.