Reading through file 4 lines at a time - python

import os
filePath = "C:\\Users\\siba\\Desktop\\1x1x1.blb"
BrickName = (os.path.splitext(os.path.basename(filePath))[0])
import sys
def ImportBLB(filePath):
file = open(filePath)
line = file.readline()
while line:
if(line == "POSITION:\n"):
POS1 = file.next()
POS2 = file.next()
POS3 = file.next()
POS4 = file.next()
sys.stdout.write(POS1)
sys.stdout.write(POS2)
sys.stdout.write(POS3)
sys.stdout.write(POS4)
return
line = file.readline()
file.close()
return
ImportBLB(filePath)
I'm attempting to read through the file four lines at a time upon locating the line "POSITION:", but this only outputs the first four lines due to the return statement ending the loop.
Removing the return statement gives me a "ValueError: Mixing iteration and read methods would lose data" error, how would I get around this?

Replace your logic with this:
with open(file_path) as f:
while True:
try:
line = next(f)
except StopIteration:
break # stops the moment you finish reading the file
if not line:
break # stops the moment you get to an empty line
if line == "POSITION:\n":
for _ in range(4):
sys.stdout.write(next(f))
edit: As your comment stated, you want 4 variables; 1 for each line. replace the last part with this:
lines = [next(f) for _ in range(4)]
This will give you a list with 4 items (the 4 lines you want) if you would prefer individual variables:
line1, line2, line3, line4 = [next(f) for _ in range(4)]

Used a little bit of both of the above suggestions, and this is now my code;
import os
filePath = "C:\Users\siba\Desktop\1x1x1.blb"
BrickName = (os.path.splitext(os.path.basename(filePath))[0])
import sys
def ImportBLB(filePath):
file = open(filePath)
line = file.next()
while line:
if(line == "POSITION:\n"):
POS1 = file.next()
POS2 = file.next()
POS3 = file.next()
POS4 = file.next()
sys.stdout.write(POS1)
sys.stdout.write(POS2)
sys.stdout.write(POS3)
sys.stdout.write(POS4)
try:
line = file.next()
except StopIteration:
break
file.close()
return
ImportBLB(filePath)

Related

Function that reads last line of file?

The function reads the last line of the file at the specified file path. The function returns the last line of the file as a string, if the file is empty it will return an empty string ("").
I tried writing my code like this but it won't work, it's pretty messy and I'm a beginner
def read_last_line(file_path):
with open(file_path, 'r') as file:
size_file = os.path.getsize(file_path)
return_file_empty = " "
last_line = (list(file)[-1])
print(last_line)
if size_file == 0:
return return_file_empty
else:
return last_line
you can use:
def read_last_line(file_path):
with open(file_path) as f:
lines = f.readlines()
return lines[-1] if lines else ''
for big files you may use:
def read_last_line(file_path):
with open(file_path, 'r') as f:
last_line = ''
for line in f:
last_line = line
return last_line
This opens the file and moves though it until there is no more file (raises StopIteration) and returns the last line.
def read_last_line(filename):
line = ""
with open(filename) as fh:
while True:
try:
line = next(fh)
except StopIteration:
return line
You can use a collections.deque to get it like the following. Unlike the currently accepted answer, doesn't require storing the entire file in memory:
from collections import deque
def get_last_line(filename):
with open(filename, 'r') as f:
try:
lastline = deque(f, 1)[0]
except IndexError: # Empty file.
lastline = None
return lastline
print('last line: {}'.format(get_last_line(filename)))
If I've understood the question correctly, something like this maybe?
def get_last_line(file_path):
with open(file_path, "r") as file:
return next(line for line in reversed(file.read().splitlines()) if line)

What is wrong with this code? I'm trying to insert this file

I am trying to insert a file and I keep getting a syntax error on the line line = infile.redline()
def main():
# Declare variables
line = ''
counter = 0
# Prompt for file name
fileName = input('Enter the name of the file: ')
# Open the specified file for reading
infile = open('test.txt', 'r')
# Priming read
line = infile.redline()
counter = 1
# Read in and display first five lines
while line != '' and counter <= 5:
# Strip '\n'
line = line.rtrip('\n')
print(line)
1ine = infile.readline()
# Update counter when line is read
counter +=1
# Close file
infile.close()
# Call the main function.
main()
rtrip should be rstrip. redline should be readline. infile.close() should be indented, and main() should not be.
However, the most serious problem is here:
1ine = infile.readline()
That first character is a one, not an L.
Knowing the standard libraries can make your life much simpler!
from itertools import islice
def main():
fname = input('Enter the name of the file: ')
with open(fname) as inf:
for line in islice(inf, 5): # get the first 5 lines
print(line.rstrip())
if __name__=="__main__":
main()
It is not redline but readline:
line = infile.redline()

Why aren't the lists populating in this code?

I wrote this code for class and cannot figure out why my lists are not populating with any values. I've tried using a debugger and still can't figure out why it won't work. Any ideas? Also... I know for loops would have made more sense, but I needed to use while loops for the assignment.
__author__ = 'Ethan'
#This program reads in a file from the user which contains lines of
def mileage():
filename = input("Please enter the file name: ")
file = open(filename,"r")
line_list = []
num_lines = sum(1 for line in file)
line_counter = 0
while line_counter <= num_lines:
line = file.readline()
line_items = line.split()
line_list.append(line_items)
line_counter += 1
current_index_pos = 0
while current_index_pos <= num_lines:
current_item = line_list[current_index_pos]
print("Leg",current_index_pos + 1,"---", current_item[0]/current_item[1],"miles/gallon")
current_index_pos += 1
mileage()
This reads to the end of the file
num_lines = sum(1 for line in file)
so there are no lines left to read when you get here
line = file.readline()
Better to structure the code like this
with open(filename, "r") as fin:
for line_counter, line in enumerate(fin):
line_items = line.split()
line_list.append(line_items)
# after the loop line_counter has counted the lines
or even (if you don't need line_counter)
with open(filename, "r") as fin:
line_list = [line.split() for line in fin]
More advanced would be to use a generator expression or do everything in a single loop to avoid needing to read the whole file into memory at once
def mileage():
filename = input("Please enter the file name: ")
with open(filename, "r") as fin:
for line_counter, line in enumerate(fin):
current_item = line.split()
print("Leg",line_counter + 1,"---", float(current_item[0])/float(current_item[1]),"miles/gallon")

Function to randomly read a line from a text file

I have to create a function that reads a random line from a text file in python.
I have the following code but am not able to get it to work
import random
def randomLine(filename):
#Retrieve a random line from a file, reading through the file irrespective of the length
fh = open(filename.txt, "r")
lineNum = 0
it = ''
while 1:
aLine = fh.readline()
lineNum = lineNum + 1
if aLine != "":
# How likely is it that this is the last line of the file ?
if random.uniform(0,lineNum)<1:
it = aLine
else:
break
fh.close()
return it
print(randomLine(testfile.txt))
I got so far but,need help to go further, Please help
once the program is running i'm getting an error saying
print(randomLine(testfile.txt))
NameError: name 'testfile' is not defined
Here's a version that's been tested to work, and avoids empty lines.
Variable names are verbose for clarity.
import random
import sys
def random_line(file_handle):
lines = file_handle.readlines()
num_lines = len(lines)
random_line = None
while not random_line:
random_line_num = random.randint(0, num_lines - 1)
random_line = lines[random_line_num]
random_line = random_line.strip()
return random_line
file_handle = None
if len(sys.argv) < 2:
sys.stderr.write("Reading stdin\n")
file_handle = sys.stdin
else:
file_handle = open(sys.argv[1])
print(random_line(file_handle))
file_handle.close()

f.seek() and f.tell() to read each line of text file

I want to open a file and read each line using f.seek() and f.tell():
test.txt:
abc
def
ghi
jkl
My code is:
f = open('test.txt', 'r')
last_pos = f.tell() # get to know the current position in the file
last_pos = last_pos + 1
f.seek(last_pos) # to change the current position in a file
text= f.readlines(last_pos)
print text
It reads the whole file.
ok, you may use this:
f = open( ... )
f.seek(last_pos)
line = f.readline() # no 's' at the end of `readline()`
last_pos = f.tell()
f.close()
just remember, last_pos is not a line number in your file, it's a byte offset from the beginning of the file -- there's no point in incrementing/decrementing it.
Is there any reason why you have to use f.tell and f.seek? The file object in Python is iterable - meaning that you can loop over a file's lines natively without having to worry about much else:
with open('test.txt','r') as file:
for line in file:
#work with line
A way for getting current position When you want to change a specific line of a file:
cp = 0 # current position
with open("my_file") as infile:
while True:
ret = next(infile)
cp += ret.__len__()
if ret == string_value:
break
print(">> Current position: ", cp)
Skipping lines using islice works perfectly for me and looks like is closer to what you're looking for (jumping to a specific line in the file):
from itertools import islice
with open('test.txt','r') as f:
f = islice(f, last_pos, None)
for line in f:
#work with line
Where last_pos is the line you stopped reading the last time. It will start the iteration one line after last_pos.

Categories

Resources