현재 텍스트 파일을 한 줄씩 읽고 특정 항목이있는 모든 줄 str
(예 : 줄에 'apple'
또는 문자열이있는 경우 'Hello World'
)을 새 텍스트 파일 로 전송하는 스크립트를 작성하려고 합니다.
fpath = open('Redshift_twb.txt', 'r')
lines = fpath.readlines()
fpath_write = open('Redshift_new.txt', 'w+')
print(lines[0:10])
fpath_write.write(lines[0:10])
fpath.close()
fpath_write.close()
현재는 기본 사항 만 설정했지만 사용할 때 .readlines()
모든 행을 별도의 색인에있는 목록에 추가 하기 때문에 문제가 발생 합니다. 그런 다음 새 파일에 다시 쓰려고하면 오류 메시지가 나타납니다.
fpath_write.write(lines[0:10])
TypeError: write() argument must be str, not list
에서 함수 .write()
를 사용할 수 없기 때문 list
입니다.
나는 이것이 두 부분으로 된 질문이라는 것을 알고 있지만, 어떤 도움이라도 대단히 감사하겠습니다.
join
그 라인 \n
-단일 문자열을 함께 꿰매기 위해fpath = open('Redshift_twb.txt', 'r')
lines = fpath.readlines()
fpath_write = open('Redshift_new.txt', 'w+')
print(lines[0:10])
# filter the list; with the string 'apple'
# replace 'apple' with whatever string you want to find
out_lines = [line for line in lines if 'apple' in line]
# Join the lines into a single string
output = '\n'.join(out_lines)
# write it
fpath_write.write(output)
fpath.close()
fpath_write.close()
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다