# Chapter 10 Exercise 2: Item Counter # This program creates a file called names.dat and then displays the number of names stored in the file # Written by Beth Mela # Last updated May 19th, 2015 # Create/ open the file for write access myFile = open("names.dat",'w') # Write to the file myFile.write("Adam\n") myFile.write("Beth\n") myFile.write("Carrie\n") myFile.write("Daniel\n") # Close the file myFile.close() # Open the file and Count the number of names stored in the file count=0 with open ('names.dat','r') as fxn: for line in fxn: count+=1 # Print the results print ('The number of names stored in this file is: {}.'.format(count))
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question