Python中write()和writelines()函数的区别
在Python中,有许多用于读取和写入文件的函数。读取和写入功能都适用于打开的文件(通过文件对象打开和链接的文件)。在本节中,我们将讨论通过文件操作数据的写入函数。
写()函数
write()函数将在文件中写入内容而不添加任何额外字符。
语法:
# Writes string content referenced by file object.
file_name.write(content)
根据语法,传递给 write()函数的字符串被写入打开的文件中。字符串可能包含数字、特殊字符或符号。在将数据写入文件时,我们必须知道 write函数不会在字符串末尾添加字符(\n)。 write()函数返回无。
例子:
Python3
file = open("Employees.txt", "w")
for i in range(3):
name = input("Enter the name of the employee: ")
file.write(name)
file.write("\n")
file.close()
print("Data is written into the file.")
Python3
file1 = open("Employees.txt", "w")
lst = []
for i in range(3):
name = input("Enter the name of the employee: ")
lst.append(name + '\n')
file1.writelines(lst)
file1.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()函数不会在字符串末尾添加字符(\n)。
例子:
Python3
file1 = open("Employees.txt", "w")
lst = []
for i in range(3):
name = input("Enter the name of the employee: ")
lst.append(name + '\n')
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
The only difference between the write() and writelines() is that write() is used to write a string to an already opened file while writelines() method is used to write a list of strings in an opened file.