file programming in python - python

read_file = open ('C:\Users\Mahya\Desktop\\automate\Autosupports\\at1.txt','r')
content = read_file.readlines()
for line in content:
if line.contains('===== BOOT TIME STATS ====='):
print found
I want to read '===== BOOT TIME STATS =====' this line and print the lines that are below till next line
please help

I'm guessing you want to print the lines between the first and second occurrences of the given string:
read_file = open ('C:\Users\Mahya\Desktop\\automate\Autosupports\\at1.txt','r')
content = read_file.readlines()
found = False
for line in content:
if line.contains('===== BOOT TIME STATS ====='):
if found:
break # Exit the for loop when finding the string for the second time
found = True
if found:
print line

Without testing:
read_file = open ('C:\Users\Mahya\Desktop\\automate\Autosupports\\at1.txt','r')
content = read_file.readlines()
i_found_the_block = False
for line in content:
if "===== BOOT TIME STATS =====" in line:
print ("found")
i_found_the_block = True
if i_found_the_block:
print line

file = open ('C:\Users\Mahya\Desktop\\automate\Autosupports\\at1.txt','r')
for line in file:
if '===== BOOT TIME STATS =====' in line: break
for line in file:
if 'i wanna stop here' in line: break
print line

def lineRange(lines, start, end):
"""Return all lines from the first line containing start
up to (but not including) the first ensuing line containing end
"""
lines = iter(lines)
# find first occurrence of start
for line in lines:
if start in line:
yield line
break
# continue until first occurrence of end
for line in lines:
if end in line:
break
else:
yield line
def main():
fname = 'C:/Users/Mahya/Desktop/automate/Autosupports/at1.txt'
start = '===== BOOT TIME STATS ====='
end = start # next section header?
with open(fname) as inf:
lr = lineRange(inf, start, end)
try:
lr.next() # skip header
print ''.join(lr)
except StopIteration:
print 'Start string not found'
if __name__=="__main__":
main()

Related

Using yield, print and return in python function

Can someone help me identify what im doing wrong below:
def SeeIfExactRangeIsFound():
with open(logfile) as input_data:
mylist = []
for line in input_data:
if BeginSearchDVar in line: # Or whatever test is needed
print line.strip()
#mylist.append((line.strip()))
#return mylist
break
for line in input_data: # This keeps reading the file
if line.strip() == EndinSearchD:
break
print line
#mylist.append((line))
#return mylist
#SeeIfExactRangeIsFound()
LRange = SeeIfExactRangeIsFound()
print LRange
I'm looping through a file and only printing out sections of that file. As in, I start printing content of logfile when a specific pattern is found in the line being read. and continue printing all lines after that first line until a line containing the pattern found in EndingSearchD variable is found.
this works with the "print". but as you can see, I want to store the output of the SeeIfExactRangeIsFound function in a variable and use the content of that variable later on.
My problem is, despite my attempts (commented out below) to try different ways to accomplish my goal, none of it seems to work. I feel I'm so close to the answer but I spent 2 hours on this and can't figure it out.
any ideas?
a version matching your description instead of your code
I start printing content of logfile when a specific pattern is found
in the line being read. and continue printing all lines after that
first line until a line containing the pattern found in EndingSearchD
variable is found.
def SeeIfExactRangeIsFound():
with open(logfile) as input_file:
input_data = input_file.readlines()
mylist = []
allow_yielding = False
for line in input_data:
if BeginSearchDVar in line:
allow_yielding = True
if allow_yielding:
yield line
if line.strip() == EndinSearchD:
break
LRange = SeeIfExactRangeIsFound()
print LRange
You almost got it, but your return statement is not in the proper scope:
def SeeIfExactRangeIsFound():
with open(logfile) as input_data:
mylist = []
for line in input_data:
if BeginSearchDVar in line: # Or whatever test is needed
print line.strip()
mylist.append((line.strip()))
break
for line in input_data: # This keeps reading the file
if line.strip() == EndinSearchD:
break
print line
mylist.append((line))
return mylist
as bonus, you can easily transform this into a generator:
def SeeIfExactRangeIsFound():
with open(logfile) as input_data:
for line in input_data:
if BeginSearchDVar in line: # Or whatever test is needed
yield line.strip()
for line in input_data: # This keeps reading the file
if line.strip() == EndinSearchD:
break
yield line
and consume it like:
results = [x for x in def SeeIfExactRangeIsFound()]

Python: Writing to file using for loop

Using this Python code I get printed lines of file in UPPERCASE but file remains unchanged (lowercase.)
def open_f():
while True:
fname=raw_input("Enter filename:")
if fname != "done":
try:
fhand=open(fname, "r+")
break
except:
print "WRONG!!!"
continue
else: exit()
return fhand
fhand=open_f()
for line in fhand:
ss=line.upper().strip()
print ss
fhand.write(ss)
fhand.close()
Can you suggest please why files remain unaffected?
Code:
def file_reader(read_from_file):
with open(read_from_file, 'r') as f:
return f.read()
def file_writer(read_from_file, write_to_file):
with open(write_to_file, 'w') as f:
f.write(file_reader(read_from_file))
Usage:
Create a file named example.txt with the following content:
Hi my name is Dmitrii Gangan.
Create an empty file called file_to_be_written_to.txt
Add this as the last line file_writer("example.txt", "file_to_be_written_to.txt") of your .py python file.
python <your_python_script.py> from the terminal.
NOTE: They all must be in the same folder.
Result:
file_to_be_written_to.txt:
Hi my name is Dmitrii Gangan.
This program should do as you requested and allows for modifying the file as it is being read. Each line is read, converted to uppercase, and then written back to the source file. Since it runs on a line-by-line basis, the most extra memory it should need would be related to the length of the longest line.
Example 1
def main():
with get_file('Enter filename: ') as file:
while True:
position = file.tell() # remember beginning of line
line = file.readline() # get the next available line
if not line: # check if at end of the file
break # program is finished at EOF
file.seek(position) # go back to the line's start
file.write(line.upper()) # write the line in uppercase
def get_file(prompt):
while True:
try: # run and catch any error
return open(input(prompt), 'r+t') # r+t = read, write, text
except EOFError: # see if user if finished
raise SystemExit() # exit the program if so
except OSError as error: # check for file problems
print(error) # report operation errors
if __name__ == '__main__':
main()
The following is similar to what you see up above but works in binary mode instead of text mode. Instead of operating on lines, it processes the file in chunks based on the given BUFFER_SIZE and can operate more efficiently. The code under the main loop may replace the code in the loop if you wish for the program to check that it is operating correctly. The assert statements check some assumptions.
Example 2
BUFFER_SIZE = 1 << 20
def main():
with get_file('Enter filename: ') as file:
while True:
position = file.tell()
buffer = file.read(BUFFER_SIZE)
if not buffer:
return
file.seek(position)
file.write(buffer.upper())
# The following code will not run but can replace the code in the loop.
start = file.tell()
buffer = file.read(BUFFER_SIZE)
if not buffer:
return
stop = file.tell()
assert file.seek(start) == start
assert file.write(buffer.upper()) == len(buffer)
assert file.tell() == stop
def get_file(prompt):
while True:
try:
return open(input(prompt), 'r+b')
except EOFError:
raise SystemExit()
except OSError as error:
print(error)
if __name__ == '__main__':
main()
I suggest the following approach:
1) Read/close the file, return the filename and content
2) Create a new file with above filename, and content with UPPERCASE
def open_f():
while True:
fname=raw_input("Enter filename:")
if fname != "done":
try:
with open(fname, "r+") as fhand:
ss = fhand.read()
break
except:
print "WRONG!!!"
continue
else: exit()
return fname, ss
fname, ss =open_f()
with open(fname, "w+") as fhand:
fhand.write(ss.upper())
Like already alluded to in comments, you cannot successively read from and write to the same file -- the first write will truncate the file, so you cannot read anything more from the handle at that point.
Fortunately, the fileinput module offers a convenient inplace mode which works exactly like you want.
import fileinput
for line in fileinput.input(somefilename, inplace=True):
print(line.upper().strip())

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()

How to find the exact length and matched string in a file using python

I have file contains
"Starting program and
Starting program
Loading molecule...
Initialising variables...
Starting the calculation - this could take a while!
Molecule energy = 2432.6 kcal mol-1
Calculation finished. Bye!"
import sys
import re
search_string = "Starting program"
txtlength=len(search_string)
print "txtlength",txtlength
lines = open( "C:\search.txt", "r" ).readlines()
for line in lines:
if re.search( search_string, line ):
print line,
else :
print "Not found"
I am looking for only 2nd line in the file but ouput coming from this code is 1 line is also displaying
You don't need regex for the example you show:
with open("C:/search.txt") as inp:
for line in inp:
if line.strip() == search_string:
print line

How to optimize this script

I have written the following script. It opens a file, reads each line from it splitting by new line character and deleting first character in line. If line exists it's being added to array. Next each element of array is splitted by whitespace, sorted alphabetically and joined again. Every line is printed because script is fired from console and writes everything to file using standard output. I'd like to optimize this code to be more pythonic. Any ideas ?
import sys
def main():
filename = sys.argv[1]
file = open(filename)
arr = []
for line in file:
line = line[1:].replace("\n", "")
if line:
arr.append(line)
for line in arr:
lines = line.split(" ")
lines.sort(key=str.lower)
line = ''.join(lines)
print line
if __name__ == '__main__':
main()
def main():
file = open(sys.argv[1])
for line in file:
if line.rstrip():
print ''.join(sorted(line[1:-1].split(), key=str.lower()))
Why create the list arr? The file is already a sequence. Why are you creating arr and not doing anything with it except iterating again.
for line in file:
line = line[1:].replace("\n", "")
if not line: continue
lines = line.split(" ")
lines.sort(key=str.lower)
line = ''.join(lines)
print line
You can condense the second loop in the first one:
import sys
def main():
filename = sys.argv[1]
file = open(filename)
for line in file:
if line.strip():
lines = line.split(" ")
lines.sort(key=str.lower)
print ''.join(lines)
if __name__ == '__main__':
main()
for small files:
import fileinput
lines = []
for line in fileinput.input():
line = line[1:].strip()
if line:
words = line.split()
words.sort(key=str.lower)
lines.append(' '.join(words))
print '\n'.join(lines)
for big files:
import fileinput
for line in fileinput.input():
line = line[1:].strip()
if line:
words = line.split()
words.sort(key=str.lower)
print ' '.join(words)
import fileinput
def main():
for line in fileinput.input():
words = line[1:].split() # strip() is redundant
if words:
words.sort(key=str.lower)
print ' '.join(words)
if __name__=="__main__":
main()

Categories

Resources