Python File Read End Of Line
Backup Exec Caso Licensing. Male Catheterisation Training Courses. Reading and Writing Files in Python. Called the EOL or End of Line character. If you want to read a file line by line. Read a file line by line. Python also has the fileinput module. Print 'Cannot read file' end if. Aug 27, 2014 readlines() is a function in python used to read text file and convert it into list where each line in at file is a element in list with new line( n).
What's wrong with your code? I find it to be quite elegant and simple. The only problem is that if the file doesn't end in a newline, the last line returned won't have a ' n' as the last character, and therefore doing line = line[:-1] would incorrectly strip off the last character of the line. The most elegant way to solve this problem would be to define a generator which took the lines of the file and removed the last character from each line only if that character is a newline: def strip_trailing_newlines(file): for line in file: if line[-1] == ' n': yield line[:-1] else: yield line f = open('myFile.txt', 'r') for line in strip_trailing_newlines(f): # do something with line. Long time ago, there was Dear, clean, old, BASIC code that could run on 16 kb core machines: like that: if (not open(1,'file.txt')) error 'Could not open 'file.txt' for reading' while(not eof(1)) line input #1 a$ print a$ wend close Now, to read a file line by line, with far better hardware and software (Python), we must reinvent the wheel: def line_input (file): for line in file: if line[-1] == ' n': yield line[:-1] else: yield line f = open('myFile.txt', 'r') for line_input(f): # do something with line I am induced to think that something has gone the wrong way somewhere.