How do you edit a text file in Python?

How do you edit a text file in Python?
Answer
Use file.readlines() to edit a file
  1. my_file = open(“data.txt”)
  2. string_list = my_file. readlines() Get file’s content as a list.
  3. my_file.
  4. print(string_list)
  5. string_list[1] = “Edit the list of strings as desiredn”
  6. my_file = open(“data.txt”, “w”)
  7. new_file_contents = “”. join(string_list) …
  8. my_file. write(new_file_contents)
 

Tìm kiếm

Back
Top