Files
PyTutorials/fileOperations.py

69 lines
1.8 KiB
Python

#This is a simple script that deals with normal file operations using a simple random number generator
##Need to add binary files to this example
import random
_NUM_TO_GENERATE = 10 #Generate this many random numbers
_BOTTOM_NUMBER = 1 #The lowest number to generate
_TOP_NUMBER = 101 #Generate numbers smaller than this
_FILE_NAME = "test.txt" #The name of the file it is working with
#Open the file
outFile = open(_FILE_NAME, "w")
print("Generating " + str(_NUM_TO_GENERATE) + " random numbers:")
randomList = [] #Keeping a list in memory of the numbers generated to compare the file against
for x in range(_NUM_TO_GENERATE):
num = random.randint(_BOTTOM_NUMBER, _TOP_NUMBER)
print(str(num)) #Print the number to the screen
outFile.write(str(num) + '\n') #Put the number in the file
randomList.append(num) #Save the number to an array
#Close the file
outFile.close()
#Print a message that you have reached the end of number generation
print("File is now closed")
print("\nOpening file for reading:")
#Open the file for reading
inFile = open(_FILE_NAME, "r")
#Read the numbers back in and print them to the screen
cnt = 0 #For keeping track of the array element
for num in inFile:
num = num.rstrip()
print(num)
if(int(num) != randomList[cnt]): #Compare to numbers in the array
print("The number " + str(num) + " did not match with the number " + str(randomList[cnt])) #Print message if numbers don't match
break #Break the loop if you had a problem reading an array element, leaving the error message as the last thing in the output
cnt += 1 #advance the array element if everything was alright
#Close the file
inFile.close()
"""Results:
Generating 10 random numbers:
14
99
48
43
23
28
81
89
29
20
File is now closed
Opening file for reading:
14
99
48
43
23
28
81
89
29
20
"""