将行写入文件的正确方法?

我习惯于print >>f, "hi there"

但是,似乎print >>已被弃用。推荐使用哪种方法进行上述操作?

更新 :关于所有带有"\n"答案... 这是通用的还是 Unix 专用的? IE,我应该在 Windows 上执行"\r\n"吗?

答案

with open('somefile.txt', 'a') as the_file:
    the_file.write('Hello\n')
from __future__ import print_function  # Only needed for Python 2
print("hi there", file=f)
f = open('myfile', 'w')
f.write('hi there\n')  # python will convert \n to os.linesep
f.close()  # you can omit in most cases as the destructor will call it
with open('file_to_write', 'w') as f:
    f.write('file contents')
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'
>>>
with open ('myfile', 'a') as f: f.write ('hi there\n')
from __future__ import print_function
print("hi there", file=f)
import time    

start = start = time.time()
with open("test.txt", 'w') as f:
    for i in range(10000000):
        # print('This is a speed test', file=f)
        # f.write('This is a speed test\n')
end = time.time()
print(end - start)
with open("test", 'w') as f:
    print('Foo1,', file=f, end='')
    print('Foo2,', file=f, end='')
    print('Foo3', file=f)
start = start = time.time()
long_line = 'This is a speed test' * 100
with open("test.txt", 'w') as f:
    for i in range(1000000):
        # print(long_line, file=f)
        # f.write(long_line + '\n')
end = time.time()

print(end - start, "s")
import pathlib

pathlib.Path('textfile.txt').write_text('content')
with open('YOURFILE.txt', 'a') as the_file:
    the_file.write('Hello')
the_file.write('Hello'+'\n')
import io
my_string = "hi there"

with io.open("output_file.txt", mode='w', encoding='utf-8') as f:
    f.write(my_string)