Another question.
This program counts and numbers every line in the code unless it has a hash tag or if the line is empty. I got it to number every line besides the hash tags. How can I stop it from counting empty lines?
def main():
file_Name = input('Enter file you would like to open: ')
infile = open(file_Name, 'r')
contents = infile.readlines()
line_Number = 0
for line in contents:
if '#' in line:
print(line)
if line == '' or line == '\n':
print(line)
else:
line_Number += 1
print(line_Number, line)
infile.close()
main()
You check if line == '' or line == '\n' inside the if clause for '#' in line, where it has no chance to be True.
Basically, you need the if line == '' or line == '\n': line shifted to the left :)
Also, you can combine the two cases, since you perform the same actions:
if '#' in line or not line or line == '\n':
print line
But actually, why would you need printing empty stings or '\n'?
Edit:
If other cases such as line == '\t' should be treated the same way, it's the best to use Tim's advice and do: if '#' in line or not line.strip().
You can skip empty lines by adding the following to the beginning of your for loop:
if not line:
continue
In Python, the empty string evaluates to the boolean value True. In case, that means empty lines are skipped because this if statement is only True when the string is empty.
The statement continue means that the code will continue at the next pass through the loop. It won't execute the code after that statement and this means your code that's counting the lines is skipped.
Related
I am creating script which reads from rockyou.txt file and the problem is that when it finishes going through all lines - 1.5M then it continues reading empty lines from the file and i need it to stop.
I can't do a simple if statement to check if the line is empty because in the file there are multiple places where there is a single empty line.
Do you have any ideas how to implement?
Code:
while line != static:
line = f.readline()
line = line.strip()
counter = counter + 1
print("Trying " + line + " Number " + str(counter))
if line == static:
print("Success")
flag = 1
break
if flag == 0:
print("Unsuccessful")
Your code attempts to read lines until a hit is found, but it doesn’t test whether the end of the file is reached.
Rewrite your code as follows to stop at the end of the file:
found = False
for line in f:
if line.strip() == static:
found = True
break
This code is omitting the counter, but it could be added back in trivially:
for counter, line in enumerate(f, 1):
line = line.strip()
print(f'Trying {line} Number {counter}')
if line == static:
found = True
break
If you have a single blank line, readline() will actually return "\n" rather than an empty string "". Thus it is safe to do this:
line = f.readline()
if not line:
break
Since bool('\n') is True. No blank lines will be skipped.
Instead of checking for 1 single empty line, check for multiple single lines. You can do this by setting another counter like this
emptyLineCounter = 0
while True:
if line == '': #Because it has been stripped,there will be no extra empty spaces
emptyLineCounter+=1
if emptyLineCounter==2: #Or any number of lines you want it to be
break
else:
emptyLineCounter = 0 #Resetting it to zero if there is text in the line
I'm testing the code below, but it doensn't do what I would like it to do.
delete_if = ['#', ' ']
with open('C:\\my_path\\AllDataFinal.txt') as oldfile, open('C:\\my_path\\AllDataFinalFinal.txt', 'w') as newfile:
for line in oldfile:
if not any(del_it in line for del_it in delete_if):
newfile.write(line)
print('DONE!!')
Basically, I want to delete any line that contains a '#' character (the lines I want to delete start with a '#' character). Also, I want to delete any/all lines that are completely blank. Can I do this in on go, by reading through items in a list, or will it require several passes through the text file to clean up everything? TIA.
It's easy. Check my code below :
filePath = "your old file path"
newFilePath = "your new file path"
# we are going to list down which lines start with "#" or just blank
marker = []
with open(filePath, "r") as file:
content = file.readlines() # read all lines and store them into list
for i in range(len(content)): # loop into the list
if content[i][0] == "#" or content[i] == "\n": # check if the line starts with "#" or just blank
marker.append(i) # store the index into marker list
with open(newFilePath, "a") as file:
for i in range(len(content)): # loop into the list
if not i in marker: # if the index is not in marker list, then continue writing into file
file.writelines(content[i]) # writing lines into file
The point is, we need to read all the lines first. And check line by line whether it starts with # or it's just blank. If yes, then store it into a list variable. After that, we can continue writing into new file by checking if the index of the line is in marker or not.
Let me know if you have problem.
How about using the ternary operator?
#First option: within your for loop
line = "" if "#" in line or not line else line
#Second option: with list comprehension
newFile = ["" if not line or "#" in line else line for line in oldfile]
I'm not sure if the ternary would work because if the string is empty, an Exception should be shown because "#" won't be in an empty string... How about
#Third option: "Staging your conditions" within your for loop
#First, make sure the string is not empty
if line:
#If it has the "#" char in it, delete it
if "#" in line:
line = ""
#If it is, delete it
else:
line = ""
I have file contains text like Hello:World
#!/usr/bin/python
f = open('m.txt')
while True:
line = f.readline()
if not line :
break
first = line.split(':')[0]
second = line.split(':')[1]
f.close()
I want to put the string after splitting it into 2 variables
On the second iteration i get error
List index out of range
it doesn't break when the line is empty , i searched the answer on related topics and the solution was
if not line:
print break
But it does not work
If there's lines after an empty line (or your text editor inserted an empty line at the end of the file), it's not actually empty. It has a new line character and/or carriage return
You need to strip it off
with open('m.txt') as f:
for line in f:
if not line.strip():
break
first, second = line.split(':')
You can do this relatively easily by utilizing an optional feature of the built-in iter() function by passing it a second argument (called sentinel in the docs) that will cause it to stop if the value is encountered while iterating.
Here's what how use it to make the line processing loop terminate if an empty line is encountered:
with open('m.txt') as fp:
for line in iter(fp.readline, ''):
first, second = line.rstrip().split(':')
print(first, second)
Note the rstrip() which removes the newline at the end of each line read.
Your code is fine, I can't put a picture in a comment. It all works, here:
I have the following file in python that I'm reading in and I want to keep track if the line is = [FOR_RECORD]. At that point I have a for loop populating an output with the value of [REG_NAME], until I reach the [/FOR_RECORD]. Then I want to go back to the start of the [FOR_RECORD] portion of the file to start populating with the next [REG_NAME]. How can I jump around in a python file like this?
Input file
--
-- generated with parser version 1.09
use ieee.std_logic_arith.all;
package [PKG_FILE]_pkg is
[FOR_RECORD]
constant [REG_NAME]_offset : std_logic_vector := x"[OFFSET]";
[/FOR_RECORD]
type [REG_NAME]_type is record
[FILED_NAME] : std_logic; -- [OFFSET] :
end record [REG_NAME]_type;
Package is [PKG_FILE]
Python code
for line in input_1:
if '[FOR_RECORD]' in line:
# This is where I want to jump to the next line
#So I can evaluate the contents
# I have 4 names in reg_name[i]
#Very important that this is nested in the if statement
for x in range(0,4):
if '[/FOR_RECORD]' in line:
break
if '[REG_NAME]' in line:
line=line.replace('[REG_NAME]',reg_name[i]['name'])
output.write(line)
output.write(line)
You can use tell to find your position in the file and seek to go to a specific position but you also have to use readline function because that for loop reads all of the lines first.
input1 = open('file')
eof = False
while (True):
while (True):
line = input1.readline()
if line == '':
eof = True
break
output.write(line)
if '[FOR_RECORD]' in line:
offset = input1.tell()
break
if eof: break
for i in range(4):
input1.seek(offset)
while (True):
line = input1.readline()
if line == '':
eof = True
break
if '[/FOR_RECORD]' in line:
break
if '[REG_NAME]' in line:
line=line.replace('[REG_NAME]',reg_name[i]['name'])
output.write(line)
if eof: break
The first loop fins the position of [FOR RECORD] line and the second iterates over elements of reg_name.
When you're iterating over a file you can use the next command to advance the iterator (retrieve the next line). So ... something like this probably gets you where you need:
for line in input_1:
if '[FOR_RECORD]' in line:
while '[/FOR_RECORD]' not in line:
line = next(input_1)
# your replacement code here.
This will iterate until it finds your begin tag, then continue to consume lines one by one until it finds your close tag, at which point you'll drop back to the outer for loop.
I would use a mini state machine. If we are between a [FOR_RECORD] and [/FOR_RECORD] lines, we should do replacement, and not if outside. Code could be:
in_record = False
for line in input_1:
if '[FOR_RECORD]' in line:
in_record = True
elif '[/FOR_RECORD]' in line:
in_record = False
elif in_record:
if '[REG_NAME]' in line:
for i in range(4):
output.write(line.replace('[REG_NAME]',
reg_name[i]['name']))
else: output.write(line)
else: output.write(line)
I have a file with the following structure:
#scaffold456
ATGTCGTGTCAGTG
GTACGTGTGTGG
+
!!!!!#!!!!!!!!
!!!!!!!!!!!!
#scaffold342
ATGGTGTCGTGGTG
ACGTGGC
+
!>!>!!!!+!!!!!
!!!!!!!
I would want an output like this:
>scaffold456
ATGTCGTGTCAGTG
GTACGTGTGTGG
>scaffold342
ATGGTGTCGTGGTG
ACGTGGC
I want to achieve this in Python, I started with the following:
fastq_filename = "test_file"
fastq = open(fastq_filename) # fastq is the file object
for line in fastq:
if line.startswith("#"):
print line.replace("#", ">")
but I can't go on anymore as I don't know:
1. How to print lines after a certain pattern match?
2. How I should specify that I want to skip lines between + till the next # sign?
This is a more complex topic in Python which I don't know, any help and explanation would be great, thanks!
fastq_filename = "test_file"
fastq = open(fastq_filename) # fastq is the file object
canPrintLines = False # Boolean state variable to keep track of whether we want to be printing lines or not
for line in fastq:
if line.startswith("#"):
canPrintLines = True # We have found an # so we can start printing lines
line = line.replace("#", ">")
elif line.startswith("+"):
canPrintLines = False # We have found a + so we don't want to print anymore
if canPrintLines:
print(line)
I don't know how complex your lines with the ! can get. I understand your question such that you wish to ignore all + and # signs inside these lines.
In that case I would introduce a state variable that stores whether we are currently working on an interesting line:
interesting_line=True
for line in fastq:
if line.strip()=='+': # Here we check for the + sign. You might need to adapt the test.
interesting_line=False # We don't care from now on
if line.startswith('#'):
interesting_line=True
if interesting_line:
# Do what you want with your line.
As I said, you might need to check if there can be situations where my simple tests don't match but this should give you a starting point
This is an easy way to do it:
for line in fastq:
if line and line[0].isalpha() or line[0]== '#':
line = line.rstrip()
print line.replace("#", ">")
Output:
>scaffold456
ATGTCGTGTCAGTG
GTACGTGTGTGG
>scaffold342
ATGGTGTCGTGGTG
ACGTGGC
for line in fastq:
if line.startswith("#") or line.isalpha():
print(line.replace("#", ">"))
Find the line that starts with # replace that with > and print it.
Then find a line that contains only letters then print that line either.
Below code will
ignore lines start with + or !
replace # with > if line start with #
write all other lines
code
def format_file(path):
new_lines = ""
for line in open(path):
if line.startswith("#"):
new_lines += line.replace("#", ">")
elif line.startswith("+"):
pass
elif line.startswith("!"):
pass
else:
new_lines += line
print new_lines
format_file("test_file")
If I'm interpreting your question correctly then I think this is what you are looking for
for line in fastq:
line = line.replace('\n','')
n = len(line)
mat = re.match(r'([ATGC]){%d}' % n,line)
if mat:
print line
if line[0] == '#':
print line.replace('#','>')
This uses Regular Expressions which are incredibly useful. This says if it is either A,T,G, or C only in a line then print that line and then the other if statement is the same as what you have. {%d} matches n number of occurrences of the previous statement, [ATGC]. If there are more than A,T,G, or C then just add them between the square brackets.