In this article let's learn how to write a Python list containing a set of elements into a text file. given a text file and a list as an input to the Python program your task is to write a logic to open the file and write the contents of the list into the file.
Let's use the file operations to perform the write operation.
Write A Python Program To Write A List Content To A File
Let's ask a user to enter a list into the Python program, take a variable and and use the input function call as a user to enter the list and convert it into an integer and store it into variable n. iterate upto to list length using the following and ask a user to enter all the list items and append it.
n = int(input("Enter List Length : "))
list1 = []
for _ in range(n):
temp = int(input("Enter List Item (Integer) : "))
list1.append(temp)
Take a file descriptor variable and use the open function call to open a file in the append mode the file name is sample as shown below and using the for loop iterate all the items, convert the items into and string using type conversion and use the write() function to write the contents of list to file.
fd_write = open("sample.txt", "a")
for item in list1:
fd_write.write(str(item))
Once the for loop is completed that means you have returned all the contents of the list into a file using the print function call print a line that is you have already returned the contents to the file and finally use the close function to close the file.
print("The List has been written to file")
fd_write.close()
We use append mode to create as well as write the contents, so make sure the next time you try to write a file, open the file in append mode just changing the open() function call line in the above statements
fd_write = open("sample.txt", "a")
The above function will open the file in an append mode so that the existing contents will not get cleaned and the new contents will be written from the immediate next line of the existing content.
Code
================
n = int(input("Enter List Length : "))
list1 = []
for _ in range(n):
temp = int(input("Enter List Item (Integer) : "))
list1.append(temp)
fd_write = open("sample.txt", "a")
for item in list1:
fd_write.write(str(item))
print("The List has been written to file")
fd_write.close()
Output
==============
Enter List Length : 5
Enter List Item (Integer) : 1
Enter List Item (Integer) : 2
Enter List Item (Integer) : 3
Enter List Item (Integer) : 4
Enter List Item (Integer) : 5
The List has been written to file
Once you run the above Python program a new file will be created in the current working directory that is sample.txt is a filename. and once you open the file using your explorer you can find the list contents present in sample.txt file
Conclusion
================
Execute the above program by providing different file names and different paths to file. comment down below if you have any suggestions to improve the above Python program.
0 Comments