By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,948 Members | 816 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,948 IT Pros & Developers. It's quick & easy.

how to count spaces in a file in python?

P: 9
I want to write a function that takes a file and a character and returns the number of character, the character is space for example.I wrote the code below but it doesn't work.
Expand|Select|Wrap|Line Numbers
  1. def c (file, char):
  2.     f = open ('file1.txt', 'r')
  3.     s = f.read()
  4.     i = 0
  5.     for char in s:
  6.         i += 1
Mar 12 '15 #1
Share this Question
Share on Google+
5 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
Maybe this will help. I have a string s with 2 commas in it.
Expand|Select|Wrap|Line Numbers
  1. >>> char = ","
  2. >>> i = 0
  3. >>> for letter in s:
  4. ...     if letter == char:
  5. ...         i+=1
  6. ...         
  7. >>> i
  8. 2
  9. >>> 
Return the character count i at the end of the function definition.
Expand|Select|Wrap|Line Numbers
  1.     return i
Mar 12 '15 #2

P: 9
thanks. but I want a function and it should take a file not a string. How should I write a function?
Mar 12 '15 #3

bvdet
Expert Mod 2.5K+
P: 2,851
It won't help you if I write the function for you. You already have a string assigned to s in the function you wrote. I gave you the for loop to count the characters. Substitute it for your for loop and add the return statement. BTW, anytime you create an open file object, it is good practice to close it when you are done. Otherwise you could read the file without creating a file object:
Expand|Select|Wrap|Line Numbers
  1. s = open('file1.txt').read()
Mar 12 '15 #4

P: 9
Expand|Select|Wrap|Line Numbers
  1. def C (file, char):
  2.     f = open ('file1.txt', 'r')
  3.     s = f.read()
  4.     i = 0
  5.     for ch in s:
  6.         if ch == char:
  7.             i += 1
  8.     return i
Mar 12 '15 #5

bvdet
Expert Mod 2.5K+
P: 2,851
thistle,

Please use code tags when posting code.

Don't forget the close the file object.
f.close()
Mar 12 '15 #6

Post your reply

Sign in to post your reply or Sign up for a free account.