Reading a File Line by Line in Python
If the idea here is to understand how to read a file line by line then all you need to do is:
with open(filename, 'r') as f:
for line in f:
print(line)
It's not typical to put this in a try-except block.Coming back to your original code there are several mistakes there which I'm assuming stem from a lack of understanding of how classes are defined/work in python.
The way you've written that code suggests you perhaps come from a Java background. I highly recommend doing one of the myriad free and really good online python courses offered on Coursera, or EdX.
Anyways, here's how I would do it using a class:
class ReadFile:
def __init__(self, path):
self.path = path
def print_data(self):
with open(self.path, 'r') as f:
for line in f:
print(line)
if __name__ == "__main__":
reader = ReadFile("H:\\Desktop\\TheFile.txt")
reader.print_data()
read a text file line by line and check for a substring on 2 of the lines
The variable line
does not magically get updated when you call f.next()
(or next(f)
in Python 3). You would instead have to assign the line returned by next
to a variable and test against it:
with open(my_file,'r') as f:
for line in f:
if 'text1' in line:
try:
next_line = next(f)
except StopIteration:
break # in case we are already at the end of file
if 'text2' in next_line:
# do some processing with line and next_line
If there can be cases where there are two consecutive lines with text1
followed by a line of text2
, however, calling next(f)
would make it consume the second line of text1
, making it unable to match text1
in the next iteration. To remedy that, you can use the pairwise
recipe in the itertools
documentation to iterate 2 lines at a time over the file instead:import itertools
def pairwise(iterable):
a, b = itertools.tee(iterable)
next(b, None)
return zip(a, b)
with open(my_file,'r') as f:
for line, next_line in pairwise(f):
if 'text1' in line and 'text2' in next_line:
# do some processing with line and next_line
Reading line by line from a file in python
You need to iterate through the file rather than the line:
#! /usr/bin/python
file = open('/home/results/err.txt')
for line in file:
print line
file.readline()
only reads the first line. When you iterate over it, you are iterating over the characters in the line. How to read a text file line by line like a set of commands
Hey I just wrote the code on repl.it you should check it out. But here is the breakdown.
- Read each line from file
Now you should a list where each element is a new line from the file
lines = ["command argument", "command argument" ... "command argument"]
Now iterate through each element in the list where you split the element at the " " (space character) and append it to a new list where all the commands and their respective arguments will be stored.
for line in lines:
commands.append(line.split(" "))Now the commands list should be a multidimensional array containing data like
commands = [["command", "argument"], ["command", "argument"], ... ["command", "argument"]]
Now you can just iterate through each sub-list where value at index 0 is the command and value at index 1 is the argument. After this you can use if statements to check for what command/ function to run with what datatype as an argument
command = []
with open("command_files.txt", "r") as f:
lines = f.read().strip().split("\n") # removing spaces on both ends, and spliting at the new line character \n
print(lines) # now we have a list where each element is a line from the file
# breaking each line at " " (space) to get command and the argument
for line in lines:
# appending the list to command list
command.append(line.split(" "))
# now the command list should be a multidimensional array
# we just have to go through each of the sub list and where the value at 0 index should be the command, and at index 1 the arguments
for i in command:
if i[0] == "print":
print(i[1])
else:
print("Command not recognized")
How to read a large file - line by line?
The correct, fully Pythonic way to read a file is the following:
with open(...) as f:
for line in f:
# Do something with 'line'
The with
statement handles opening and closing the file, including if an exception is raised in the inner block. The for line in f
treats the file object f
as an iterable, which automatically uses buffered I/O and memory management so you don't have to worry about large files.There should be one -- and preferably only one -- obvious way to do it.
how do i read a text file in line-by-line using Python when the formatting is specific
You can store all of the points from line 3 and beyond in a list of lists.
You just need to replace:
# parse remaining lines
.
.
.
# having trouble here...
.
.
.
with:line = list()
points = list()
for i in range(2,len(data)):
line.extend(data[i].split())
points = [line[x:x+3] for x in range(0, len(line),3)]
or if you want to store each of them as separate lists, you can do the following:x = list()
y = list()
pen = list()
for i in range(2,len(data)):
line = data[i].split()
for j in range(len(line)):
if j%3 == 0:
x.append(line[j])
elif j%3 == 1:
y.append(line[j])
else:
pen.append(line[j])
You can make plots easily this way. python read from text file line by line
This script loads the file into dataset
list:
dataset = []
with open(filename, 'r') as f_in:
for items in f_in:
dataset.append(items.split())
print(dataset)
Prints:[['a', 'b', 'c'], ['b', 'c'], ['a', 'b', 'c'], ['d'], ['b', 'c']]
Related Topics
Nan Loss When Training Regression Network
How to Get All the Request Headers in Django
Filtering a Pyspark Dataframe with SQL-Like in Clause
Python Insert Numpy Array into SQLite3 Database
Why Does the Floating-Point Value of 4*0.1 Look Nice in Python 3 But 3*0.1 Doesn'T
Use Index in Pandas to Plot Data
Python: Why Does ("Hello" Is "Hello") Evaluate as True
Pivot Tables or Group by for Pandas
Setting Variables with Exec Inside a Function
How to Release Memory After Creating Matplotlib Figures
Suppressing Scientific Notation in Pandas
How to Handle Exceptions in a List Comprehensions
Typeerror: Got Multiple Values for Argument
How to Import a Module in Python with Importlib.Import_Module