This document discusses writing and reading data from text files in Python. It demonstrates opening a file in write, append, and read modes. It writes sample text and random numbers to files, then reads the data back and calculates statistics like minimum, maximum, average values.
This document discusses writing and reading data from text files in Python. It demonstrates opening a file in write, append, and read modes. It writes sample text and random numbers to files, then reads the data back and calculates statistics like minimum, maximum, average values.
This document discusses writing and reading data from text files in Python. It demonstrates opening a file in write, append, and read modes. It writes sample text and random numbers to files, then reads the data back and calculates statistics like minimum, maximum, average values.
2. 3. #Saving a string to a textfile 4. fn = open("D:/Temp/data.txt", "w") 5. fn.write("Python is a great language! ") 6. fn.close() 7. 8. # add to the file 9. fn = open("D:/Temp/data.txt", "a") 10. fn.write("Especially for Engineers and Scientists.") 11. fn.close() 12. 13. input("Press a key to read the file...") 14. 15. # read from the file and display it 16. fn = open("D:/Temp/data.txt", "r") 17. str = fn.read() 18. print(str) 19. fn.close() 20. 21. 22. #Saving random data to a textfile 23. import random as r 24. 25. numberOfValues = 200 26. sum=0 27. rnd=[] 28. 29. for a in range(0,numberOfValues): 30. rnd.append(r.randint(1,100)) 31. 32. for x in range(0,len(rnd)): 33. sum += rnd[x] 34. avg = sum/len(rnd) 35. 36. path = "D:/Temp/randata.txt" 37. fn = open(path, "w") 38. 39. for a in range(0,len(rnd)): 40. s=str(rnd[a]) + "," 41. fn.write(s) 42. fn.write("\n\n") 43. fn.write("Analysis:\n") 44. fn.write("Number of values = {} \n".format(len(rnd))) 45. fn.write("Maximum value = {} \n".format(max(rnd))) 46. fn.write("Minimum value = {} \n".format(min(rnd))) 47. fn.write("Average value = {}".format(round(avg,2))) 48. 49. fn.close()