Exercise41

Write a program in Python which create from a given list a text file whose lines are the elements of this list. Example if the list is:

List_programming_books = ["Python programming books", "Java programming books", "C ++ programming books", "C # programming books"]

, the generated file will be formed by the lines:
Python programming books
Java programming books
C ++ programming books
C # programming books

Solution

List_programming_books = ["Python programming books", "Java programming books", "C ++ programming books", "C # programming books"]

# oen a text file in write mode as f
with open('programming_books.txt', 'w') as f:
    
    # iterate over all element in the list
    for book in List_programming_books:
        
        # create a new line by adding line
        line = book + "\n"
        f.write(line)
"""
After the loop is complete, the file is automatically closed and saved. The text file programming_books.txt will be saved in the same directory as the Python program, and will contain the lines:
Python programming books
Java programming books
C ++ programming books
C # programming books
"""





In this program:

  1. we define first the list: List_programming_books which contains the names of programming books.
  2. We then use a with statement: to open a file called programming_books.txt in write mode ('w').
  3. The with statement: ensures that the file is properly closed after we're done with it.
  4. We then loop through each book: in the list using a for loop, and write each book to a new line in the text file using the write method of the file object.
  5. we then add "\n": to add line break after the line
  6. Finally we use write methode: to write the line in file text.

 

Younes Derfoufi
my-courses.net

Leave a Reply