큰 txt 파일에 1 백만 줄이 포함되어 있습니다. 각 줄을 작은 txt 파일로 나누고 싶습니다. 파이썬을 사용하는 방법은 무엇입니까? 나는 몇 가지 관련 질문을 발견하고이 같은 코드를 가지고 :큰 txt 파일을 파이썬을 사용하여 줄 단위로 작은 txt 파일로 분할하는 방법
def split_file(filepath, lines=30):
"""Split a file based on a number of lines."""
path, filename = os.path.split(filepath)
# filename.split('.') would not work for filenames with more than one .
basename, ext = os.path.splitext(filename)
# open input file
with open(filepath, 'r') as f_in:
try:
# open the first output file
f_out = open(os.path.join(path, '{}_{}{}'.format(basename, 0, ext)), 'w')
# loop over all lines in the input file, and number them
for i, line in enumerate(f_in):
# every time the current line number can be divided by the
# wanted number of lines, close the output file and open a
# new one
if i % lines == 0:
f_out.close()
f_out = open(os.path.join(path, '{}_{}{}'.format(basename, i, ext)), 'w')
# write the line to the output file
f_out.write(line)
finally:
# close the last output file
f_out.close()
그러나 그것은 단지 작은 txt 파일의 기능을하지만 내 목표 파일에 작동하지 않습니다, 나는 그 이유를 알 수없는 오류 정보가 없습니다.
우리는 당신을 위해 몇 가지 코드를 작성하고자합니다. 대부분의 사용자는 곤경에 처한 코더 코드를 기꺼이 만들지 만 일반적으로 포스터가 이미 문제를 해결하려고 시도했을 때만 도움이됩니다. 이러한 노력을 입증하는 좋은 방법은 지금까지 작성한 코드, 예제 입력 (있는 경우), 예상 출력 및 실제로 얻은 출력 (출력, 역 추적 등)을 포함시키는 것입니다. 더 자세하게 제공할수록 더 많은 답변을받을 수 있습니다. [FAQ] (http://stackoverflow.com/tour) 및 [How to Ask] (http://stackoverflow.com/questions/how-to-ask)를 확인하십시오. – TigerhawkT3
지금까지 해보신 것은 무엇입니까? 과제 중 어느 부분에 문제가 있습니까? – EJoshuaS
감사를 업데이트했습니다 – zjsuper