Python file.write 创建额外的回车 [英] Python file.write creating extra carriage return

查看:27
本文介绍了Python file.write 创建额外的回车的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python 将一系列 SQL 语句写入文件.模板字符串如下所示:

I'm writing a series of SQL statements to a file using python. The template string looks like:

store_insert = '\tinsert stores (storenum, ...) values (\'%s\', ...)'

我正在像这样写入文件:

I'm writing to the file like so:

for line in source:
    line = line.rstrip()
    fields = line.split('\t')
    script.write(store_insert % tuple(fields))
    script.write(os.linesep)

但是,在结果输出中,我在每一行的末尾看到 \r\r\n,而不是我期望的 \r\n.为什么?

However, in the resulting output, I see \r\r\n at the end of each line, rather than \r\n as I would expect. Why?

推荐答案

\n 转换为 os.linesep 以文本模式打开的文件.因此,当您将 os.linesep 写入 Windows 上的文本模式文件时,您会写入 \r\n,并且 \n 会被转换导致 \r\r\n.

\n is converted to os.linesep for files opened in text-mode. So when you write os.linesep to a text-mode file on Windows, you write \r\n, and the \n gets converted resulting in \r\r\n.

另见文档:

在写入以文本模式(默认)打开的文件时,不要使用 os.linesep 作为行终止符;在所有平台上改用单个\n".

Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.

这篇关于Python file.write 创建额外的回车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆