programing

Python과 줄바꿈을 사용하여 파일에 목록 작성

shortcode 2022. 10. 26. 22:44
반응형

Python과 줄바꿈을 사용하여 파일에 목록 작성

파일에 목록을 작성하려면 어떻게 해야 합니까? writelines()에서는 줄 바꿈 문자가 삽입되지 않으므로 다음 작업을 수행해야 합니다.

f.writelines([f"{line}\n" for line in lines])

루프 사용:

with open('your_file.txt', 'w') as f:
    for line in lines:
        f.write(f"{line}\n")

Python <3.6의 경우:

with open('your_file.txt', 'w') as f:
    for line in lines:
        f.write("%s\n" % line)

Python 2의 경우 다음 항목을 사용할 수도 있습니다.

with open('your_file.txt', 'w') as f:
    for line in lines:
        print >> f, line

호출에 이 있는, 각 괄호 "는 .[]listcomp genexp. 전체 문자열 목록을 구현하기 위해 필요한 메모리를 모두 사용할 필요가 없습니다.

그 파일을 어떻게 할 거예요?이 파일은 사람 또는 상호운용성 요건이 명확한 다른 프로그램용으로 존재합니까?

나중에 같은 python 앱에서 사용할 수 있도록 목록을 디스크에 직렬화하려고 한다면 목록을 피클해야 합니다.

import pickle

with open('outfile', 'wb') as fp:
    pickle.dump(itemlist, fp)

다시 읽으려면:

with open ('outfile', 'rb') as fp:
    itemlist = pickle.load(fp)

심플한 것은 다음과 같습니다.

with open("outfile", "w") as outfile:
    outfile.write("\n".join(itemlist))

항목 목록의 모든 항목이 문자열인지 확인하려면 생성기 식을 사용합니다.

with open("outfile", "w") as outfile:
    outfile.write("\n".join(str(item) for item in itemlist))

하세요.itemlist메모리를 차지하기 때문에, 메모리 소비량에 주의해 주세요.

Python 3 및 Python 2.6+ 구문 사용:

with open(filepath, 'w') as file_handler:
    for item in the_list:
        file_handler.write("{}\n".format(item))

이것은 플랫폼에 의존하지 않습니다.또한 UNIX의 베스트 프랙티스인 줄바꿈 문자로 마지막 행을 끝냅니다.

.6 , Python 3.6 "{}\n".format(item)으로 대체할 수 있습니다.f"{item}\n".

또 다른 방법이군simplejson(python 2.6에 json으로 포함)을 사용하여 json으로 직렬화합니다.

>>> import simplejson
>>> f = open('output.txt', 'w')
>>> simplejson.dump([1,2,3,4], f)
>>> f.close()

출력을 검사하는 경우.txt:

[1, 2, 3, 4]

이것은 구문이 피조어이고 사람이 읽을 수 있고 다른 언어로 된 다른 프로그램에서 읽을 수 있기 때문에 유용합니다.

genexp를 사용하면 어떤 이점이 있는지 알아보는 것도 재미있을 것 같아서 제 의견을 말씀드리겠습니다.

질문의 예에서는 대괄호를 사용하여 임시 목록을 작성합니다.따라서 다음과 같습니다.

file.writelines( list( "%s\n" % item for item in list ) )

명령어는 쓸 의 임시 을 불필요하게 에 따라 할 수 .목록의 크기와 출력의 상세 내용에 따라서는, 대량의 메모리가 소비될 가능성이 있습니다.str(item) empty.month.mpti.

를.list()위의 호출)은 대신 임시 발전기를 에 전달합니다.file.writelines():

file.writelines( "%s\n" % item for item in list )

の inated this thisinatedationationation의 줄 바꿈표현을 .item온디맨드 객체(즉, 기입된 대로).여기에는 몇 가지 이유가 있습니다.

  • 메모리 오버헤드는 매우 큰 목록이라도 작습니다.
  • 한다면str(item)각 항목이 처리될 때 파일에 가시적인 진행이 있습니다.

이것에 의해, 다음과 같은 메모리 문제가 회피됩니다.

In [1]: import os

In [2]: f = file(os.devnull, "w")

In [3]: %timeit f.writelines( "%s\n" % item for item in xrange(2**20) )
1 loops, best of 3: 385 ms per loop

In [4]: %timeit f.writelines( ["%s\n" % item for item in xrange(2**20)] )
ERROR: Internal Python error in the inspect module.
Below is the traceback from this internal error.

Traceback (most recent call last):
...
MemoryError

(이 에러는 Python의 최대 가상 메모리를 최대 100MB로 제한하여 트리거했습니다.ulimit -v 102400).

메모리 사용량을 한쪽으로 미루면 이 방법은 원래 방식보다 빠르지는 않습니다.

In [4]: %timeit f.writelines( "%s\n" % item for item in xrange(2**20) )
1 loops, best of 3: 370 ms per loop

In [5]: %timeit f.writelines( ["%s\n" % item for item in xrange(2**20)] )
1 loops, best of 3: 360 ms per loop

(Linux의 경우 Python 2.6.2)

귀찮아서...

import json
a = [1,2,3]
with open('test.txt', 'w') as f:
    f.write(json.dumps(a))

#Now read the file back into a Python list object
with open('test.txt', 'r') as f:
    a = json.loads(f.read())

쉼표로 구분된 값을 사용하여 목록을 텍스트 파일로 직렬화합니다.

mylist = dir()
with open('filename.txt','w') as f:
    f.write( ','.join( mylist ) )

일반

다음은 writlines() 메서드의 구문입니다.

fileObject.writelines( sequence )

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "rw+")
seq = ["This is 6th line\n", "This is 7th line"]

# Write sequence of lines at the end of the file.
line = fo.writelines( seq )

# Close opend file
fo.close()

언급

http://www.tutorialspoint.com/python/file_writelines.htm

python>3에서는print그리고.*인수의 압축을 푸는 경우

with open("fout.txt", "w") as fout:
    print(*my_list, sep="\n", file=fout)

심플:

with open("text.txt", 'w') as file:
    file.write('\n'.join(yourList))
file.write('\n'.join(list))

사용.numpy.savetxt다음 옵션도 있습니다.

import numpy as np

np.savetxt('list.txt', list, delimiter="\n", fmt="%s")
with open ("test.txt","w")as fp:
   for line in list12:
       fp.write(line+"\n")

python3에 있는 경우 다음과 같이 프린트 기능을 사용할 수도 있습니다.

f = open("myfile.txt","wb")
print(mylist, file=f)

한번 해보지 그래?

file.write(str(list))

나는 최근에 경로가 유용하다는 것을 알았다.그래야 할 필요가 없어집니다.with open('file') as f그리고 파일에 씁니다.이것이 누군가에게 도움이 되기를 바랍니다:).

from pathlib import Path
import json
a = [[1,2,3],[4,5,6]]
# write
Path("file.json").write_text(json.dumps(a))
# read
json.loads(Path("file.json").read_text())

이 논리는 먼저 목록의 항목을 다음과 같이 변환합니다.string(str)때때로 리스트에는 다음과 같은 태플이 포함되어 있습니다.

alist = [(i12,tiger), 
(113,lion)]

이 로직은 각 태플을 새로운 행으로 파일에 기록합니다.나중에 사용할 수 있습니다.eval파일을 읽을 때 각 태플을 로드하는 동안:

outfile = open('outfile.txt', 'w') # open a file in write mode
for item in list_to_persistence:    # iterate over the list items
   outfile.write(str(item) + '\n') # write to the file
outfile.close()   # close the file 

다음 작업도 수행할 수 있습니다.

예:

my_list=[1,2,3,4,5,"abc","def"]
with open('your_file.txt', 'w') as file:
    for item in my_list:
        file.write("%s\n" % item)

출력:

your_file.txt항목은 다음과 같이 저장됩니다.

1

2

3

4

5

abc

def

스크립트도 위와 같이 저장됩니다.

아니면 피클을 사용하셔도 됩니다.

import pickle
my_list=[1,2,3,4,5,"abc","def"]
#to write
with open('your_file.txt', 'wb') as file:
    pickle.dump(my_list, file)
#to read
with open ('your_file.txt', 'rb') as file:
    Outlist = pickle.load(file)
print(Outlist)

출력: [1, 2, 3, 4, 5, 'abc', 'def']

읽을 수 있는 목록을 로드할 때 목록과 동일하게 덤프됩니다.

또, 에 의해서simplejson상기의 출력과 같은 가능성이 있다.

import simplejson as sj
my_list=[1,2,3,4,5,"abc","def"]
#To write
with open('your_file.txt', 'w') as file:
    sj.dump(my_list, file)

#To save
with open('your_file.txt', 'r') as file:
    mlist=sj.load(file)
print(mlist)

줄바꿈을 반복하고 추가하는 또 다른 방법:

for item in items:
    filewriter.write(f"{item}" + "\n")

Python3에서는 이 루프를 사용할 수 있습니다.

with open('your_file.txt', 'w') as f:
    for item in list:
        f.print("", item)

stdout을 파일로 리디렉션하는 것도 이러한 목적으로 유용할 수 있습니다.

from contextlib import redirect_stdout
with open('test.txt', 'w') as f:
  with redirect_stdout(f):
     for i in range(mylst.size):
        print(mylst[i])

나는 이 해결책을 제안합니다.

with open('your_file.txt', 'w') as f:        
    list(map(lambda item : f.write("%s\n" % item),my_list))   

avg를 리스트로 합니다.

In [29]: a = n.array((avg))
In [31]: a.tofile('avgpoints.dat',sep='\n',dtype = '%f')

사용할 수 있습니다.%e또는%s당신의 필요에 따라.

이런 답을 찾으시는 것 같아요.

f = open('output.txt','w')
list = [3, 15.2123, 118.3432, 98.2276, 118.0043]
f.write('a= {:>3d}, b= {:>8.4f}, c= {:>8.4f}, d= {:>8.4f}, e= 
{:>8.4f}\n'.format(*list))
f.close()
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
f = open('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file

구조: 먼저 내장된 오픈 기능을 사용하여 파일 이름과 파일 열기 모드를 지정하여 파일을 엽니다.모드는 읽기 모드('r'), 쓰기 모드('w') 또는 추가 모드('a')일 수 있습니다.텍스트 모드('t') 또는 이진 모드('b')에서 읽기, 쓰기 또는 추가 여부를 지정할 수도 있습니다.그 밖에도 많은 모드를 사용할 수 있습니다.도움말(열기)을 클릭하면 자세한 내용이 표시됩니다.기본적으로는 open()은 considersle을 t'ext file로 간주하여 r'ead 모드로 엽니다.이 예에서, 우리는 먼저 쓰기 텍스트 모드에서 일(一)을 열고 일(一) 객체의 쓰기 방법을 사용하여 일(一)에 쓴 다음 일(一)을 완전히 닫는다.

위의 예는 Swaroop C H의 저서 "A Byte of Python"에서 나온 것입니다. swaroopch.com

언급URL : https://stackoverflow.com/questions/899103/writing-a-list-to-a-file-with-python-with-newlines

반응형