在运行Windows XP专业版的Python 2.7中:
import csv
outfile = file('test.csv', 'w')
writer = csv.writer(outfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['hi','dude'])
writer.writerow(['hi2','dude2'])
outfile.close()
Run Code Online (Sandbox Code Playgroud)
它生成一个文件test.csv,每行有一个额外的\ r \n,如下所示:
hi,dude\r\r\nhi2,dude2\r\r\n
Run Code Online (Sandbox Code Playgroud)
而不是预期的:
hi,dude\r\nhi2,dude2\r\n
Run Code Online (Sandbox Code Playgroud)
为什么会发生这种情况,或者这实际上是期望的行为?
我知道我可以用以下内容写一个CSV文件:
with open('some.csv', 'w', newline='') as f:
Run Code Online (Sandbox Code Playgroud)
我如何将该输出写入STDOUT?
我需要将从 Python 调用的 PowerShell stdout 解码为 Python 字符串。
\n\n我的最终目标是以字符串列表的形式获取 Windows 上网络适配器的名称。我当前的函数如下所示,并且在使用英语的 Windows 10 上运行良好:
\n\ndef get_interfaces():\n ps = subprocess.Popen(['powershell', 'Get-NetAdapter', '|', 'select Name', '|', 'fl'], stdout = subprocess.PIPE)\n stdout, stdin = ps.communicate(timeout = 10)\n interfaces = []\n for i in stdout.split(b'\\r\\n'):\n if not i.strip():\n continue\n if i.find(b':')<0:\n continue\n name, value = [ j.strip() for j in i.split(b':') ]\n if name == b'Name':\n interfaces.append(value.decode('ascii')) # This fails for other users\n return interfaces\nRun Code Online (Sandbox Code Playgroud)\n\n其他用户使用不同的语言,因此value.decode('ascii')其中一些用户会失败。例如,一位用户报告说更改为decode('ISO 8859-2')对他来说效果很好(因此它不是 …
我想通过 Windows CMD(控制台)从 Python 中使用类似 UNIX EOL (LF) 的管道文本。然而,Python 似乎会自动将单个换行符转换为 Windows 风格的行尾 (EOL)字符(即\r\n, <CR><LF>, 0D 0A, 13 10):
#!python3
#coding=utf-8
import sys
print(sys.version)
print("one\ntwo")
# run as py t.py > t.txt
Run Code Online (Sandbox Code Playgroud)
结果是
3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)]
one
two
Run Code Online (Sandbox Code Playgroud)
或十六进制... 6F 6E 65 0D 0A 74 77 6F 0D 0A
第二个 EOL 是因为
print()默认为end='\n',但它也会进行转换。
print没有newline像 for 那样的参数或属性open(),那么如何控制它呢?
python ×3
windows ×3
newline ×2
python-3.x ×2
csv ×1
eol ×1
powershell ×1
stdout ×1
subprocess ×1
unicode ×1