We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent bc19702 commit db3ca26Copy full SHA for db3ca26
2 files changed
projects/Random_word_from_list/Random_word_from_list.py
@@ -0,0 +1,24 @@
1
+import sys
2
+import random
3
+
4
+if sys.argv[1:]:
5
+ filename = sys.argv[1] # check if filename is supplied as a command line argument
6
+else:
7
+ filename = input("What is the name of the file? (extension included): ")
8
9
+try:
10
+ file = open(filename)
11
+except:
12
+ print("File doesn't exist!") # handle exception
13
+ exit()
14
15
+num_lines = sum(1 for line in file if line.rstrip()) # get number of lines
16
17
+random_line = random.randint(0, num_lines) # generate a random number between possible interval
18
19
+file.seek(0) # re-iterate from first line
20
21
+for i, line in enumerate(file):
22
+ if i == random_line:
23
+ print(line.rstrip()) # rstrip removes any trailing newlines :)
24
+ break
0 commit comments