如何在现代Python中向文件写入一行?我听说这是不赞成的:
print >>f, "hi there"
另外,“\n”在所有平台上都可以工作吗,还是我应该在Windows上使用“\r\n”?
如何在现代Python中向文件写入一行?我听说这是不赞成的:
print >>f, "hi there"
另外,“\n”在所有平台上都可以工作吗,还是我应该在Windows上使用“\r\n”?
当前回答
从3.5开始,你也可以使用pathlib来实现这个目的:
路径。write_text(data, encoding=None, errors=None) 以文本模式打开指向的文件,向其写入数据,然后关闭文件:
import pathlib
pathlib.Path('textfile.txt').write_text('content')
其他回答
您应该使用print()函数,该函数自Python 2.6+以来可用
from __future__ import print_function # Only needed for Python 2
print("hi there", file=f)
对于Python 3,您不需要导入,因为print()函数是默认的。
Python 3中的替代方法是使用:
with open('myfile', 'w') as f:
f.write('hi there\n') # python will convert \n to os.linesep
引用自Python文档中关于换行符的内容:
当写入输出到流时,如果newline为None,则写入的任何'\n'字符都将转换为系统默认的行分隔符os.linesep。如果换行符为''或'\n',则不进行转换。如果newline是任何其他合法值,则写入的任何'\n'字符都将转换为给定的字符串。
参见:读取和写入文件- Python教程
你也可以试试文件编辑器
PIP安装文件写入器
from filewriter import Writer
Writer(filename='my_file', ext='txt') << ["row 1 hi there", "row 2"]
写入my_file.txt
接受一个可迭代对象或具有__str__支持的对象。
关于os.linesep:
下面是一个在Windows上精确的未经编辑的Python 2.7.1解释器会话:
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.linesep
'\r\n'
>>> f = open('myfile','w')
>>> f.write('hi there\n')
>>> f.write('hi there' + os.linesep) # same result as previous line ?????????
>>> f.close()
>>> open('myfile', 'rb').read()
'hi there\r\nhi there\r\r\n'
>>>
在Windows上:
不出所料,os。linesep不会产生与'\n'相同的结果。它不可能产生同样的结果。'hi there' + os。linesep等价于'hi there\r\n',它并不等价于'hi there\n'。
很简单:使用\n,它会自动转换为os.linesep。自从第一次将Python移植到Windows以来,就一直如此简单。
使用os没有任何意义。linesep在非Windows系统上,它在Windows上产生错误的结果。
不要使用os.linesep!
当我需要大量编写新行时,我定义了一个使用print函数的lambda:
out = open(file_name, 'w')
fwl = lambda *x, **y: print(*x, **y, file=out) # FileWriteLine
fwl('Hi')
这种方法的好处是它可以利用打印函数的所有可用特性。
更新:正如Georgy在评论区提到的,可以通过partial函数进一步改进这个想法:
from functools import partial
fwl = partial(print, file=out)
恕我直言,这是一种更实用、更简单的方法。
你也可以这样使用io模块:
import io
my_string = "hi there"
with io.open("output_file.txt", mode='w', encoding='utf-8') as f:
f.write(my_string)