Programing

파일에 줄을 쓰는 올바른 방법?

lottogame 2020. 9. 28. 07:55
반응형

파일에 줄을 쓰는 올바른 방법?


나는하는 데 익숙하다 print >>f, "hi there"

그러나 print >>더 이상 사용되지 않는 것 같습니다 . 위의 줄을 수행하는 데 권장되는 방법은 무엇입니까?

업데이트 : 모든 답변과 관련하여 "\n"...이 범용입니까 아니면 유닉스 전용입니까? IE, "\r\n"Windows 에서해야 합니까?


이것은 다음과 같이 간단해야합니다.

with open('somefile.txt', 'a') as the_file:
    the_file.write('Hello\n')

문서에서 :

os.linesep텍스트 모드 (기본값)에서 열린 파일을 쓸 때 줄 종결 자로 사용하지 마십시오 . 모든 플랫폼에서 대신 단일 '\ n'을 사용하십시오.

유용한 자료 :


print()Python 2.6 이상부터 사용할 수 있는 함수를 사용해야합니다.

from __future__ import print_function  # Only needed for Python 2
print("hi there", file=f)

Python 3의 import경우 print()함수가 기본값 이므로는 필요하지 않습니다 .

대안은 다음을 사용하는 것입니다.

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

개행에 관한 Python 문서 에서 인용 :

출력에서 newline이 None이면 '\n'쓰여진 모든 문자는 시스템 기본 줄 구분 기호 os.linesep. 개행이 ''이면 번역이 수행되지 않습니다. newline이 다른 유효한 값 중 하나이면 '\n'작성된 모든 문자가 주어진 문자열로 변환됩니다.


파이썬 문서는 이 방법을 권장합니다 :

with open('file_to_write', 'w') as f:
    f.write('file contents')

그래서 이것이 제가 보통하는 방식입니다. :)

docs.python.org의 성명 :

파일 객체를 다룰 때 'with' 키워드 를 사용하는 것이 좋습니다 . 이는 도중에 예외가 발생하더라도 제품군이 완료된 후 파일이 제대로 닫히는 이점이 있습니다. 또한 동등한 try-finally 블록을 작성하는 것보다 훨씬 짧습니다.


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는 않습니다 NOT 과 같은 결과를 생산 '\n'. 동일한 결과를 얻을 수있는 방법은 없습니다. 'hi there' + os.linesep에 해당 'hi there\r\n'되는, 하지 에 해당 'hi there\n'.

It's this simple: use \n which will be translated automatically to os.linesep. And it's been that simple ever since the first port of Python to Windows.

There is no point in using os.linesep on non-Windows systems, and it produces wrong results on Windows.

DO NOT USE os.linesep!


I do not think there is a "correct" way.

I would use:

with open ('myfile', 'a') as f: f.write ('hi there\n')

In memoriam Tim Toady.


In Python 3 it is a function, but in Python 2 you can add this to the top of the source file:

from __future__ import print_function

Then you do

print("hi there", file=f)

If you are writing a lot of data and speed is a concern you should probably go with f.write(...). I did a quick speed comparison and it was considerably faster than print(..., file=f) when performing a large number of writes.

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)

On average write finished in 2.45s on my machine, whereas print took about 4 times as long (9.76s). That being said, in most real-world scenarios this will not be an issue.

If you choose to go with print(..., file=f) you will probably find that you'll want to suppress the newline from time to time, or replace it with something else. This can be done by setting the optional end parameter, e.g.;

with open("test", 'w') as f:
    print('Foo1,', file=f, end='')
    print('Foo2,', file=f, end='')
    print('Foo3', file=f)

Whichever way you choose I'd suggest using with since it makes the code much easier to read.

Update: This difference in performance is explained by the fact that write is highly buffered and returns before any writes to disk actually take place (see this answer), whereas print (probably) uses line buffering. A simple test for this would be to check performance for long writes as well, where the disadvantages (in terms of speed) for line buffering would be less pronounced.

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")

The performance difference now becomes much less pronounced, with an average time of 2.20s for write and 3.10s for print. If you need to concatenate a bunch of strings to get this loooong line performance will suffer, so use-cases where print would be more efficient are a bit rare.


Since 3.5 you can also use the pathlib for that purpose:

Path.write_text(data, encoding=None, errors=None)

Open the file pointed to in text mode, write data to it, and close the file:

import pathlib

pathlib.Path('textfile.txt').write_text('content')

When you said Line it means some serialized characters which are ended to '\n' characters. Line should be last at some point so we should consider '\n' at the end of each line. Here is solution:

with open('YOURFILE.txt', 'a') as the_file:
    the_file.write('Hello')

in append mode after each write the cursor move to new line, if you want to use 'w' mode you should add '\n' characters at the end of write() function:

the_file.write('Hello'+'\n')

One can also use the io module as in:

import io
my_string = "hi there"

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

You can also try filewriter

pip install filewriter

from filewriter import Writer

Writer(filename='my_file', ext='txt') << ["row 1 hi there", "row 2"]

Writes into my_file.txt

Takes an iterable or an object with __str__ support.


When I need to write new lines a lot, I define a lambda that uses a print function:

out = open(file_name, 'w')
fwl = lambda *x, **y: print(*x, **y, file=out) # FileWriteLine
fwl('Hi')

This approach has the benefit that it can utilize all the features that are available with the print function.

Update: As is mentioned by Georgy in the comment section, it is possible to improve this idea further with the partial function:

from functools import partial
fwl = partial(print, file=out)

IMHO, this is a more functional and less cryptic approach.

참고URL : https://stackoverflow.com/questions/6159900/correct-way-to-write-line-to-file

반응형