Iterating Through Text File Only Printing First Line - python

I am trying to check if the variable 'account' is in a text file (variable 'line'). I iterated through the file and printed out 'line'. Doing so allowed be to print the whole text file. I then added if statement to check if an account is in the file and did a print as well. Only the first line of the text file printed when i used that last 'if' statement.
for account, email,master_name in zip(account_numbers, email_address,master_name):
fbl_acct_check_q = f"""SELECT * FROM TEST
WHERE account_no = '{account.replace("-","")}'"""
fblacctcursor.execute(fbl_acct_check_q)
for col_acct_fbl_check in fblacctcursor.fetchall():
account_status = col_acct_fbl_check[6]
with open(sumbstatementfilepath) as sbfile:
lines = sbfile.readlines()
for line in lines:
line = line.split()
print(line)
if account_status == 4 and account not in line:
fbl_account_email()
print(line)
break

Related

How do I delete a certain line (given a line #) in a file through python?

I want to delete a line of text from a .txt file given an integer corresponding to the txt file's line number. For example, given the integer 2, delete line 2 of the text file.
I'm sort of lost on what to put into my program.
f = open('text1.txt','r+')
g = open('text2.txt',"w")
line_num = 0
search_phrase = "Test"
for line in f.readlines():
line_num += 1
if line.find(search_phrase) >= 0:
print("text found a line" , line_num)
decision = input("enter letter corresponding to a decision: (d = delete lines, s = save to new txt) \n")
if decision == 'd':
//delete the current line
if decision == 's':
//save the current line to a new file
Any help is appreciated! Thanks :)
This way:
with open('text1.txt','r') as f, open('text2.txt',"w") as g:
to_delete=[2,4]
for line_number, line in enumerate(f.readlines(), 1):
if line_number not in to_delete:
g.write(line)
else:
print(f'line {line_number}, "{line.rstrip()}" deleted')
Here it goes.
f = open('data/test.txt','rb')
text = f.readlines() # all lines are read into a list and you can acess it as a list
deleted_line = text.pop(1) #line is deleted and stored into the variable
print(text)
print(deleted_line)
f.write(text) # here you save it with the new data, you can always delete the data in the file to replace by the new one

read and get specific int line of the text file into variable on python

a_file = open('file.txt')
string = 'a word'
flag = 0
index = 0
for line in a_file:
index += 1
if string in line:
break
index -= 1
lines_to_read = [index]
for position, line in enumerate(a_file):
if position in lines_to_read:
file = line
print(line)
I found the line where 'a word' is located, and I want to get those line into a variable
but it only reads the first line of the text file
how can I fix it
You can simply iterate through the lines, and assign the line to a previous created string variable, if the condition is met, that the string occurs in a line of the file:
a_file = open('file.txt')
string = 'a word'
res_line = ""
for line in a_file:
if string in line:
res_line = line
print(res_line)
a_file.close()
you could also create a list which contains every line in that the string occurs:
a_file = open('file.txt')
string = 'a word'
res = [line for line in a_file if string in line]
print(res)
a_file.close()
#Maicon has it, though in python you don't even need the global variable, you can create and set desired_line in the if statement and its namespace will extend to the entire function containing the if statement:
a_file = open('file.txt')
string = 'a word'
for line in a_file:
if string in line:
desired_line = line
break
print(desired_line)
a_file.close()
What you can do is check for string in the line. This will do for you.
a_file = open('all.txt')
string = 'a word'
flag = 0
index = 0
for position, line in enumerate(a_file):
if string in line: #=== if 'a word' in line
file = line
pos=position+1
break
print(file,"Line Number: ",pos)
However if more number of the same words are there, you can use a dict to get the line numbers and the value.
a_file = open('all.txt')
string = 'f'
dictionary={}
flag = 0
index = 0
for position, line in enumerate(a_file):
if string in line:
file = line
pos=position
dictionary.update({pos+1:[file.strip("\n").strip(),file.count(string)]})
if dictionary!={}:
print("\n------- Statistics --------\n")
print("Total Items found: ",len(dictionary),"\nTotal Occurences: ",sum([dictionary.get(x)[1] for x in dictionary]))) #=== Get the sum of all numbers
for key, value in dictionary.items():
print("-------------------------")
print("Line: "+value[0],"\nNumber of occurrences: ",value[1],"\nLine Number: ",key)
else:
print("Oops. That word was no found. Check you word again.")

Replace line in text file using python

This is my program:
filetest = open ("testingfile.txt", "r+")
ID = input ("Enter ID: ")
list = ['Hello', 'Testing', 'File', 543210]
for line in filetest:
line = line.rstrip ()
if not ID in line:
continue
else:
templine = '\t'.join(map(str, list))
filetest.write (line.replace(line, templine))
filetest.close ()
I'm trying to replace an entire line containing the ID entered in filetest with templine (templine was a list joined into a string with tabs), and I think the problem with my code is specifically this part filetest.write (line.replace(line, templine)), because when I run the program, the line in the file containing ID doesn't get replaced, but rather templine is added to the end of the line.
For example, if the line in filetest found using the ID entered was "Goodbye\tpython," now it becomes "Goodbye\tpythonHello\tTesting\tFile\t543210" which is not what I want. How do I ensure that line "Goodbye\tpython" is replaced by templine "Hello\tTesting\tFile\t543210", not appended?
As you are reading from the file the file pointer moves as well and it can cause problems. What I would do is first read the file and prepare the "new file" that you want, and then write it into the file, as shown in the code below:
filetest = open ("testingfile.txt", "r")
lines = filetest.readlines()
filetest.close()
ID = input ("Enter ID: ")
list = ['Hello', 'Testing', 'File', 543210]
for i in range(len(lines)):
lines[i] = lines[i].rstrip()
if ID not in lines[i]:
continue
else:
templine = '\t'.join(map(str, list))
lines[i] = templine
with open("testingfile.txt", "w") as filetest:
for line in lines:
filetest.write(line + "\n")
I didn't change the logic of the code but be aware that if your file has, for example, a line with the number "56" and a line with the number "5", and you enter the ID "5", then the code will replace both of those lines.

Python Reading a text file

I wrote an applescript to generate a text file of all unwatched movies in my itunes library. Here is the code of that script:
tell application "iTunes"
set watchedEpisodes to tracks of playlist "TV Shows" whose unplayed is false and played count > 0
set unwatchedEpisodes to tracks of playlist "TV Shows" whose unplayed is true
if (count unwatchedEpisodes) > 0 then
set trackNames to {}
repeat with anEpisode in unwatchedEpisodes
set tmp to location of anEpisode as text
set posixtmp to POSIX path of tmp
set end of trackNames to (posixtmp as text)
end repeat
set {TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, return}
set unwatchedTVShows to trackNames as text
do shell script "echo " & quoted form of unwatchedTVShows & " > /Volumes/Data/Media/Kodi/unwatchedTVShows.txt"
#display dialog trackNames as text
set AppleScript's text item delimiters to TID
end if
set watchedEpisodes to tracks of playlist "Movies" whose unplayed is false and played count > 0
set unwatchedEpisodes to tracks of playlist "Movies" whose unplayed is true
if (count unwatchedEpisodes) > 0 then
set trackNames to {}
repeat with anEpisode in unwatchedEpisodes
set tmp to location of anEpisode as text
set posixtmp to POSIX path of tmp
set end of trackNames to (posixtmp as text)
end repeat
set {TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, return}
set unwatchedMovies to trackNames as text
do shell script "echo " & quoted form of unwatchedMovies & " > /Volumes/Data/Media/Kodi/unwatchedMovies.txt"
#display dialog trackNames as text
set AppleScript's text item delimiters to TID
end if
end tell
Here is my output file:
/Volumes/Data/Media/Movies/Thanks For Sharing.m4v
/Volumes/Data/Media/Movies/Thats My Boy.m4v
/Volumes/Data/Media/Movies/Think Like a Man.m4v
/Volumes/Data/Media/Movies/Think Like a Man Too.m4v
/Volumes/Data/Media/Movies/This Means War.m4v
/Volumes/Data/Media/Movies/Top Five.m4v
/Volumes/Data/Media/Movies/Trail of Blood.m4v
My problem is reading this file. I need to open it, and put it in a string so that I can search it wholeistically (ie, if I search for "Think Like a Man" I don't want a false positive on "Think Like a Man Too".
Anyway, here is my current python code (or at least a snippet of that code):
KODIFOLDER="/Volumes/Data/Media/Kodi"
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as umovies:
for line in umovies:
line = line.strip()
print line
Here is the output:
/Volumes/Data/Media/Movies/Trail of Blood.m4voo.m4v
Clearly, it's opening and reading the file, but I'm not understanding why the snippet isn't providing a full "list" of what's in the text file. Any thoughts as to what I'm doing wrong?
Here is the final answer. Not sure exactly what's different than what I had before (mixing tabs and spaces maybe??). Anyway, for future reference, this code:
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as uwmovies:
for line in uwmovies:
line = line.replace("\n","")
unwatchedmovies = line.split('\r')
print unwatchedmovies
Gave the output of this list:
['/Volumes/Data/Media/Movies/Table 19.m4v', '/Volumes/Data/Media/Movies/Term Life.m4v', '/Volumes/Data/Media/Movies/Thanks For Sharing.m4v', '/Volumes/Data/Media/Movies/Thats My Boy.m4v', '/Volumes/Data/Media/Movies/Think Like a Man.m4v', '/Volumes/Data/Media/Movies/Think Like a Man Too.m4v', '/Volumes/Data/Media/Movies/This Means War.m4v', '/Volumes/Data/Media/Movies/Top Five.m4v', '/Volumes/Data/Media/Movies/Trail of Blood.m4v']
which was exactly what I needed. I list with no "\r" or "\n"'s. Thanks for the help!
Is this your actual code snippet?
KODIFOLDER="/Volumes/Data/Media/Kodi"
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as umovies:
for line in umovies:
line = line.strip()
print line
This would only print the last line of your file. Note, print line is only indented one tab.
Try calling .read() on the file you open and then split the content up on \n (newline)
KODIFOLDER="/Volumes/Data/Media/Kodi"
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as umovies:
for line in umovies.read().split('\n'):
line = line.strip()
print line
But this is probably enough for your usecase:
KODIFOLDER="/Volumes/Data/Media/Kodi"
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as umovies:
umovies_content = umovies.read()
print umovies_content
Try This ( Pythonic Way, UPDATED ) :
import sys
read_lines = [sys.stdout.write(line.rstrip('\n') + "\n") for line in open('1.txt')]
Python 2x
from __future__ import print_function
read_lines = [print(line.rstrip('\n')) for line in open('1.txt')]

How to find and replace different strings in a file at a time?

As per my know this may work for one condition but it is clears my file and replacing the find string in file.
#!/usr/bin/python
open('vpc.xml','r+') as p: #open a file in read and write mode
p=rp.readlines()
print p #printing what content read by p
for line in p: #for loop up to end of line in file
if "<mac address=" in line: #if condition encounter by for loop line then it replaces the string specified in if condition.
print line
r.write(line.replace("<mac address=","<mac address1="))
elif "<source bridge=" in line:
print line
r.write(line.replace("<source bridge=","<source bridge1="))
elif "<target dev" in line:
print line
r.write(line.replace("<target dev","<target dev1"))
else :
print 'no changes'
continue
#!/usr/bin/python
o = input("enter how many vpcs")
y = input("enter how many eth interfaces")
for k in range(1,o):
h='vpc'+str(k)+'.xml'
print h
#j = input("enter how many eth interfaces")
ri=open(h,'r')
line = ri.read()
ri.close()
for i in range(0,y)
for s in range(i+1)
dev_val={'network':'bridge','<man':'<manneth0','<man':'vpc'+str(i)+_eth+str(i),}
for key,val in dev_val.items():
line = line.replace(key,val)
print line
with open(h,'w') as v:
v.write(line)
v.close()

Categories