'White'
needs to be changed to 'Williams'
in accounts.txt
, the old name cannot simply be overwrittenWhite
is stored as300 White 0.00
'White'
with the name 'Williams'
, the record becomes300 Williams00
i
” in 'Williams'
overwrite other characters in the line300 White 0.00
into a temporary file, 300 White 0.00
to the temporary file, .txt
¶accounts.txt
file to change account 300’s name from 'White'
to 'Williams'
as described above: accounts = open('accounts.txt', 'r')
temp_file = open('temp_file.txt', 'w')
with accounts, temp_file:
for record in accounts:
account, name, balance = record.split()
if account != '300':
temp_file.write(record)
else:
new_record = ' '.join([account, 'Williams', balance])
temp_file.write(new_record + '\n')
.txt
(cont.)¶with
statement manages two resource objects, specified in a comma-separated list after with
'300'
, we write record
(which contains a newline) to temp_file
'Williams'
in place of 'White'
and write it to the file# macOS/Linux Users: View file contents
!cat temp_file.txt
# Windows Users: View file contents
!more temp_file.txt
os
Module File-Processing Functions¶accounts.txt
file, then rename temp_file.txt
as accounts.txt
import os
os.remove('accounts.txt')
rename
function to rename the temporary file as 'accounts.txt'
os.rename('temp_file.txt', 'accounts.txt')
# macOS/Linux Users: View file contents
!cat accounts.txt
# Windows Users: View file contents
!more accounts.txt
©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.
DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.