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