What I want to express right now is For example, Start with file=open('test.txt','w') and write only 8 random numbers from 1 to 100. (1,52,77,32,98,23,65,49) And I want to make a new test2.txt file by reading this test.txt file and sorting the large number first How do I write it down, !
file=open('test2.txt','w') Should I write file.read('test.txt')?
You can compare numbers with a for statement But I don't know how to make a new file again by reading the existing file :(
python
# Write down 8 randomly
with open('test2.txt','w') as f:
f.write('1,52,77,32,98,23,65,49')
# Create a sorted list from a large number and write it to the test.txt file
with open('test2.txt') as f:
test = f.read() # test == '1,52,77,32,98,23,65,49'
test = test.split(',') # test == ['1','52','77','32','98','23','65','49']
test.sort(reverse=1) # test == ['98','77','65','52','49','32','23','1']
test = ','.join(test) # test == '98,77,65,52,49,32,23,1'
print(test)
with open('test.txt','w') as result:
result.write(test)
© 2024 OneMinuteCode. All rights reserved.