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:
- we define first the list: List_programming_books which contains the names of programming books.
- We then use a with statement: to open a file called programming_books.txt in write mode ('w').
- The with statement: ensures that the file is properly closed after we're done with it.
- 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.
- we then add "\n": to add line break after the line
- Finally we use write methode: to write the line in file text.
Younes Derfoufi
my-courses.net