Python에는 파일을 읽고 쓰는 데 필요한 많은 함수가 있습니다. 읽기 및 쓰기 기능은 모두 열린 파일(파일 개체를 통해 열리고 연결된 파일)에서 작동합니다. 이 섹션에서는 파일을 통해 데이터를 조작하는 쓰기 기능에 대해 설명합니다.
쓰기() 함수
write() 함수는 추가 문자를 추가하지 않고 파일에 내용을 씁니다.
통사론 :
선택 정렬
# Writes string content referenced by file object. file_name.write(content)>
구문에 따라 write() 함수에 전달된 문자열이 열린 파일에 기록됩니다. 문자열에는 숫자, 특수 문자 또는 기호가 포함될 수 있습니다. 파일에 데이터를 쓰는 동안 쓰기 함수는 문자열 끝에 개행 문자( )를 추가하지 않는다는 것을 알아야 합니다. write() 함수는 None을 반환합니다.
예:
파이썬3
file> => open>(>'Employees.txt'>,>'w'>)> > for> i>in> range>(>3>):> >name>=> input>(>'Enter the name of the employee: '>)> >file>.write(name)> >file>.write(>'
'>)> > file>.close()> > print>(>'Data is written into the file.'>)> |
>
>
산출:
Data is written into the file.>
샘플 실행:
Enter the name of the employee: Aditya Enter the name of the employee: Aditi Enter the name of the employee: Anil>
writelines() 함수
이 함수는 목록의 내용을 파일에 씁니다.
통사론 :
# write all the strings present in the list 'list_of_lines' # referenced by file object. file_name.writelines(list_of_lines)>
구문에 따라 writelines() 함수에 전달된 문자열 목록이 열린 파일에 기록됩니다. write() 함수와 마찬가지로 writelines() 함수는 문자열 끝에 개행 문자( )를 추가하지 않습니다.
예:
파이썬3
file1>=> open>(>'Employees.txt'>,>'w'>)> lst>=> []> for> i>in> range>(>3>):> >name>=> input>(>'Enter the name of the employee: '>)> >lst.append(name>+> '
'>)> > file1.writelines(lst)> file1.close()> print>(>'Data is written into the file.'>)> |
>
>
산출:
Data is written into the file.>
샘플 실행:
Enter the name of the employee: Rhea Enter the name of the employee: Rohan Enter the name of the employee: Rahul>
유일한 차이점은 쓰다() 그리고 쓰기 라인() write()는 이미 열린 파일에 문자열을 쓰는 데 사용되고 writelines() 메서드는 열린 파일에 문자열 목록을 쓰는 데 사용됩니다.