Python, checking a .txt file for a filename - python

I,m a extreme noobie...
I making a dowsing program.
I have code that randomly picks a image file from a directory. (I can do this)
i need to know how to write the file path of the image to a txt file. (simple database)
Then next time read the txt file to see if that file has been selected in the last 100 entries, if it has been selected, how to make it go back to the random module and try again until it gets one that has yet to be selected in the 100 times.
Thanks
sample
os.chdir('C:\landscapes\pics')
left1 = random.choice(os.listdir("C:\landscapes\pics"))
# TEST FILE
print(left1)
os.chdir('C:\landscapes')
logfile = open('test.txt', 'r')
loglist = logfile.readlines()
logfile.close()
found = False
for line in loglist:
if str(left1) in line:
print ("Found it")
found = True
if not found:
logfile = open('test.txt', 'a')
logfile.write(str(left1)+"\n")
logfile.close()
print ("Not Found!")
I,m able to tell if the file is found or not.
I,m just at a loss of what to do next, I think I need kind of While loop?

You don't need a while loop. Instead, this can be achieved with self referencing methods, which create a sort-of, infinite loop, until a certain condition is met (i.e.: found = False). Also, I took out the references to os.chdir as you don't need those if you specify the directory you are attempting to search in the path of os.listdir, and open().
def choose_random_file():
return random.choice(os.listdir("C:\landscapes\pics"))
def validate_randomness( random_file ):
logfile = open('C:\landscapes\test.txt', 'r')
loglist = logfile.readlines()
logfile.close()
found = False
for line in loglist:
if str( random_file ) in line:
print ("Found it")
found = True
# we found the file, now break out of the for loop
break
# Check if we found the file
if found:
# If we found the file name, then circle-back to pick another file
random_file = choose_random_file()
# Now validate that the new pick is in the test.txt file again
validate_randomness( random_file )
if not found:
logfile = open('test.txt', 'a')
logfile.write(str( random_file )+"\n")
logfile.close()
print ("Not Found!")
random_file = choose_random_file()
validate_randomness( random_file )
Hope this helps point you in the right direction. Let me know if something doesn't work.

Related

Python with statement issue

New to python and found one box still running very old code that doesn't support the with statement and admins not interested in upgrading as it will be replaced, but no ETA on replacement and need to get my script working
On another box with later version script works fine, but need to get it working on this older box
Extract from working script on later version
with open("ping.log","r") as reader:
while True:
line = reader.readline()
if len(line)==0:
break
status = line[34]
name = line[16:30]
if (status=="d"):
html+= '<tr>\n<td>\n<font color="red">'+ name+'</font><br>\n</td>\n</tr>\n'
else:
html+= '<tr>\n<td>\n<font color="green">'+ name+'</font><br>\n</td></tr>\n'
It basically opens file reads the contents and looks at specific position to see if device is up or down and make it red or green
Now I know you can use something like
fileh = open(file, 'w')
try:
# Do things with fileh here
finally:
fileh.close()
Need help with the part between try and finally
The as fileh part needs to be changed to an assignment to the file handle variable you want to use, reader, and that basically fixes it.
To wit,
reader = open("ping.log", 'r') # not 'w' if you are reading
try:
# Do things with reader here
# Basically copy-paste the stuff which was inside the with statement
finally:
reader.close()
You were actually on the right path:
fileh = open("ping.log", 'r') # you don't need the as reader part
try:
for line in fileh: # you can just iterate over the file, no need for while True
if len(line)==0:
break
status = line[34]
name = line[16:30]
if (status == "d"):
html+= '<tr>\n<td>\n<font color="red">'+ name+'</font><br>\n</td>\n</tr>\n'
else:
html+= '<tr>\n<td>\n<font color="green">'+ name+'</font><br>\n</td></tr>\n'
except:
print("ERROR")
finally:
fileh.close()
You could even make a variable color and set it depending on your status, so the lines are easier to change later like:
...
color = "red" if (status == "d") else "green"
html+= '<tr>\n<td>\n<font color="' + color + '">'+ name + '</font><br>\n</td>\n</tr>\n'
...
EDIT: As suggested, I updated for try, except, finally
EDIT 2:
For your second problem, as I understand it, you want to write or append to the file dash.aspx?
Then you wouldn't have to iterate over it
...
writer = open("dash.apsx", "w") #You need to check whether you want to use 'a' or 'w' for appending or writing
#no need to iterate over writerlines, you already have the file and can directly write to it
#INFO: this will put everything on one line, for new lines you could add "\n" e.g. writer.write(htmlBeg + "\n") etc.
writer.write(htmlBeg)
writer.write("<tr>")
writer.write(htmlTBeg)
writer.write('<th style="text-align:left"><h3>APAC Region Firewalls</h3></th>')
writer.write(html)
writer.write(htmlTEnd)
#close file at the end
write.close()
...

Trying to use os.path.exists via variables but getting an error

I have a file called serial.dll. The content of this file is another file's name:
a-2ED1-7156.dll
I also have 1 file called a-2ED1-7156.dll in the same directory.
When I try to check if the file exists by reading its name from serial.dll:
f = open('serial.dll', 'r')
serials = f.read()
if os.path.exists(serials):
print("ok")
else:
print("no")
Always results "no".
but:
file = 'a-2ED1-7156.dll'
if os.path.exists(file):
print("ok")
else:
print("no")
Always gives the correct result.
How can I check if the file a-2ED1-7156.dll exists by reading it from the serial.dll file?
Update Try:
f = open('serial.dll', 'r')
lines = f.readline()
for line in lines:
if os.path.exists(line):
print('ok')
else:
print("no")
results error:
no
no
no
no
no
no
no
no
no
no
no
ok
no
no
no
no
Supossing each file is in a separate line, you coud use
lines = f.readlines()
for line in lines:
if os.path.exists(line):
print('ok')
Or print only if all files exist, depending on what you want exactly.
Your problem is that lines in a file might end with the new-line character. File names usually don't have that character... For example, right now you're checking if the file a-2ED1-7156.dll\n exists - which is not. You simply need to strip() the lines before checking them as files:
f = open('serial.dll')
for line in f:
filename = line.strip()
if os.path.exists(filename):
print(f"{filename} exists")
else:
print(f"{filename} doesn't exist")

How to automatically update a list of filenames in Python

I have a list of filenames: files = ["untitled.txt", "example.txt", "alphabet.txt"]
I also have a function to create a new file:
def create_file(file):
"""Creates a new file."""
with open(file, 'w') as nf:
is_first_line = True
while True:
line = input("Line? (Type 'q' to quit.) ")
if line == "q":
# Detects if the user wants to quuit.
time.sleep(5)
sys.exit()
else:
line = line + "\n"
if is_first_line == False:
nf.write(line)
else:
nf.write(line)
is_first_line = False
I want the list to update itself after the file is created. However, if I just filenames.append() it,
I realized that it would only update itself for the duration of the program. Does anybody know how to do this? Is this possible in Python?
"Is this possible in Python?" -> This has nothing to do with limitations of the language you chose to solve your problem. What you want here is persistence. You could just store the list of files in a text file. Instead of hardcoding the list in your code your program would then read the content every time it is run.
This code could get you started:
with open("files.txt") as infile:
files = [f.strip() for f in infile.readlines()]
print(f"files: {files}")
# here do some stuff and create file 'new_file'
new_file = 'a_new_file.txt'
files.append(new_file)
###
with open("files.txt", "w") as outfile:
outfile.write("\n".join(files))

Format path within Text File for consumption in Python

I am writing a Python script for use by multiple non-Python users.
I have a text file containing the parameters my script needs to run.
One of the inputs is a path. I cannot get my script to run and was thinking it was because I had referenced my path incorrectly.
I have tried:
C:\temp\test
"C:\temp\test"
r"C:\temp\test"
C:/temp/test
"C:/temp/test"
C:\\temp\\test
"C:\\temp\\test"
I have added each one of these into a text file, which is called and read in my Python script.
I have other parameters and they are called correctly, my script seems to run when I hard code the path in. I say seems because I think there are a few bugs I need to check, but it runs with no errors.
When I use the text file I get this error - which varies depending on if I used one of the above examples:
WindowsError: [Error 123] The filename, directory name, or volume
label syntax is incorrect: 'c:\temp\match1\jpg\n/.'
My code is as follows:
print ("Linking new attachments to feature")
fp = open(r"C:\temp\Match1\Match_Table.txt","r") #reads my text file with inputs
lines=fp.readlines()
InFeat = lines[1]
print (InFeat)
AttFolder = lines[3] #reads the folder from the text file
print (AttFolder)
OutTable = lines[5]
if arcpy.Exists(OutTable):
print("Table Exists")
arcpy.Delete_management(OutTable)
OutTable = lines[5]
print (OutTable)
LinkF = lines[7]
print (LinkF)
fp.close()
#adding from https://community.esri.com/thread/90280
if arcpy.Exists("in_memory\\matchtable"):
arcpy.Delete_management("in_memory\\matchtable")
print ("CK Done")
input = InFeat
inputField = "OBJECTID"
matchTable = arcpy.CreateTable_management("in_memory", "matchtable")
matchField = "MatchID"
pathField = "Filename"
print ("Table Created")
arcpy.AddField_management(matchTable, matchField, "TEXT")
arcpy.AddField_management(matchTable, pathField, "TEXT")
picFolder = r"C:\temp\match1\JPG" #hard coded in
print (picFolder)
print ("Fields added")
fields = ["MatchID", "Filename"]
cursor = arcpy.da.InsertCursor(matchTable, fields)
##go thru the picFolder of .png images to attach
for file in os.listdir(picFolder):
if str(file).find(".jpg") > -1:
pos = int(str(file).find("."))
newfile = str(file)[0:pos]
cursor.insertRow((newfile, file))
del cursor
arcpy.AddAttachments_management(input, inputField, matchTable, matchField, pathField, picFolder)
From your error "'c:\temp\match1\jpg\n/.'", i can see "\n" character, \n is symbole of new line ( when you press enter button ) you should remove that character from end of your path! did you try to do that? you can use .lstrip("\n") , replcae() or regx methods for remove that character.
Try to open and read line by line of your input file like this:
read_lines = [line.rstrip('\n') for line in open(r"C:\temp\Match1\Match_Table.txt")]
print(read_lines)
print(read_lines[1])

Line count of decoded binary content from json response

I have some code below that counts the number of lines in decoded GitHub binary content and then looks for percent change based on the changes count of a file. This is contained in a loop within a loop in an if/else statement. What I have now works, but it outputs the results of each individual file in the pull request. I would like to write the if/else just once if any of the results in the set of returned files meet the condition in the if statement (else print no file has changed) and then move on to the next set for evaluation.
found = False
for data in repo.pull_request(prs.number).files():
if data.filename.endswith((".png",".jpeg",".gif")):
pass
else:
for files_content in [repo.blob(data.sha)]:
binary_coded_content = io.BytesIO((base64.b64decode(files_content.content)))
tempfile = 'temp'
with open(tempfile,'wb') as f:
f.write(binary_coded_content.read())
num_lines = sum(1 for line in open(tempfile, encoding='utf8') if line.rstrip())
if data.changes_count/num_lines > 0.25:
found = True
break
if found:
print("A file has changed by more than 25%", '\n')
else:
print("No file has changed by more than 25%", '\n')
If I understand correctly you want to create a found variable and test it outside the loop like this
found = False # <----
for data in repo.pull_request(prs.number).files():
if data.filename.endswith((".png",".jpeg",".gif")):
pass
else:
for files_content in [repo.blob(data.sha)]:
binary_coded_content = io.BytesIO((base64.b64decode(files_content.content)))
tempfile = 'temp'
with open(tempfile,'wb') as f:
f.write(binary_coded_content.read())
num_lines = sum(1 for line in open(tempfile, encoding='utf8') if line.rstrip())
if data.changes_count/num_lines > 0.25:
found = True # <----
break #<--- break inner loop
if found:
break #<--- break outer loop
if found: # after the loop ended, we check if we found something...
print("A file has changed by more than 25%")
else:
print("No file has changed by more than 25%")

Categories

Resources