Advertisement
open('filename', mode);
File Mode | Description |
---|---|
w | Searches for the file and opens it in write mode. If the file is found, its contents are overwritten. If file is not found, a new file is created. Allows you to write to the file. |
Methods | Description |
---|---|
write(str) | The write() method writes a string(str) value to a file. |
writelines(lines) | The writelines() method writes a list of lines to a file. |
Advertisement
# Python - Creating a file for performing for the write operation.
# Calling the open() function to open a file named File1.txt in write mode
file = open('File1.txt', 'w')
# Creating 3 strings and appending the newline character \n at their end
str1 = 'Hello World! \n'
str2 = 'Welcome to DecodeJava \n'
str3 = 'Hope you like our tutorials \n'
# Writing the first string value to the file using the write() method of file object
file.write(str1)
# Writing the second value to the file using the write() method of file object
file.write(str2)
# Writing the third string value to the file using the write() method of file object
file.write(str3)
# Closing the file after completing the write operation on it
file.close()
Hello World!
Welcome to DecodeJava!
Hope you like our tutorials.
# Python - Writing a file by taking input from user at console
# Calling the open() function to open a file named File2.txt in write mode
file = open('File2.txt', 'w')
# Creating 3 strings
str1 = input('What is the capital of Finland? : ')
str2 = input('What is tallest building in the world? : ')
str3 = input('What is the densest forst in the world? : ')
# Writing the first string value to the file using the write() method of file object
file.write(str1 + '\n')
# Writing the second value to the file using the write() method of file object
file.write(str2 + '\n')
# Writing the third string value to the file using the write() method of file object
file.write(str3 + '\n')
# Closing the file after completing the write operation on it
file.close()
What is the capital of Finland? : Helsinki
What is tallest building in the world? : Burj Khalifa
What is the densest forst in the world? : Amazon Basin
Helsinki
Burj Khalifa
Amazon Basin
# Python - Writing to a file using writelines() method
# Calling the open() function to open a file named File3.txt in write mode
file = open('File3.txt', 'w')
# Creating 3 strings and appending the newline character \n at their end
str1 = 'Hello World! \n'
str2 = 'Can you answer a question? \n'
str3 = 'Which came first - Chicken or Egg? \n'
# Creating a list of lines, where each line is a string value.
a_list = [str1, str2, str3]
# Writing a list of lines to the file using the writelines() method of file object
file.writelines(a_list)
# Closing the file after completing the write operation on it
file.close()
Hello World!
Can you answer a question?
Which came first - Chicken or Egg?
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement