Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a single character at a time from a file in Python?

Can anyone tell me how can I do this?

like image 396
kaushik Avatar asked Jun 07 '10 09:06

kaushik


People also ask

How do I read a single character from a file?

fgetc() function in C fgetc() function is a file handling function in C programming language which is used to read a character from a file. It reads single character at a time and moves the file pointer position to the next address/location to read the next character.

How do you read a character from a string in Python?

Individual characters in a string can be accessed by specifying the string name followed by a number in square brackets ( [] ). String indexing in Python is zero-based: the first character in the string has index 0 , the next has index 1 , and so on.

What is the method to read a single line at a time from the file?

We can use java.io.BufferedReader readLine() method to read file line by line to String. This method returns null when end of file is reached. Below is a simple program showing example for java read file line by line using BufferedReader.


2 Answers

with open(filename) as f:   while True:     c = f.read(1)     if not c:       print "End of file"       break     print "Read a character:", c 
like image 115
jchl Avatar answered Oct 12 '22 03:10

jchl


First, open a file:

with open("filename") as fileobj:     for line in fileobj:          for ch in line:             print(ch) 

This goes through every line in the file and then every character in that line.

like image 23
Raj Avatar answered Oct 12 '22 01:10

Raj