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])
Related
I need to define a fucntion that will, in short:
Open and grab the content from an existing file
Transform that content
Create a new file
Write that new content in this new file
Print the content of the new file
I'm a complete begginer, but I got this until now. How can I improve this?
def text():
#open the existing file
text_file = open('music.txt', 'r')
#reads the file
reading = text_file.read ()
#this turns everything to lower case, counts the words and displays the list vertically
from collections import Counter
new_text = reading.lower()
list_words = Counter(new_text.split())
ordered_list = sorted(list_words.items())
#creates a new file and writes the content there
with open('finheiro_saida.txt', 'x') as final_file:
for i in ordem:
finheiro_saida.write(str(i) + '\n')
#not sure how to open this new file and print its content, when I tried it says the new file doesn't exist in the directory - tried everything.
final = open('C:/Users/maria/OneDrive/Documents/SD_DTM/ficheiro_saida.txt', 'r')
read_file = final.read ()
print(read_file)
You can open the new file and print its content the same way you read and wrote to it!
# ...After all your previous code...
with open('finheiro_saida.txt', 'r') as final_file:
final_file_content = final_file.read()
print(final_file_content)
Fixed some syntax error in your code.
you can display the the same way you read.
Also provide all imports to the start of the file.
you can also read all lines from the file as a list using file.readlines()
from collections import Counter
def text():
# open the existing file
text_file = open("music.txt", "r")
# reads the file
reading = text_file.read()
# this turns everything to lower case, counts the words and displays the list vertically
new_text = reading.lower()
list_words = Counter(new_text.split())
ordered_list = sorted(list_words.items())
# creates a new file and writes the content there
file_name = "finheiro_saida.txt"
with open("finheiro_saida.txt", "x") as final_file:
for i in ordered_list:
final_file.write(str(i) + "\n")
return file_name
def display(final_file_name):
with open(final_file_name) as file:
print(file.read())
final_file_name = text()
display(final_file_name)
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.
I can't figure out how to write the user input to an existing file. The file already contains a series of letters and is called corpus.txt . I want to take the user input and add it to the file , save and close the loop.
This is the code I have :
if user_input == "q":
def write_corpus_to_file(mycorpus,myfile):
fd = open(myfile,"w")
input = raw_input("user input")
fd.write(input)
print "Writing corpus to file: ", myfile
print "Goodbye"
break
Any suggestions?
The user info code is :
def segment_sequence(corpus, letter1, letter2, letter3):
one_to_two = corpus.count(letter1+letter2)/corpus.count(letter1)
two_to_three = corpus.count(letter2+letter3)/corpus.count(letter2)
print "Here is the proposed word boundary given the training corpus:"
if one_to_two < two_to_three:
print "The proposed end of one word: %r " % target[0]
print "The proposed beginning of the new word: %r" % (target[1] + target[2])
else:
print "The proposed end of one word: %r " % (target[0] + target[1])
print "The proposed beginning of the new word: %r" % target[2]
I also tried this :
f = open(myfile, 'w')
mycorpus = ''.join(corpus)
f.write(mycorpus)
f.close()
Because I want the user input to be added to the file and not deleting what is already there, but nothing works.
Please help!
Open the file in append mode by using "a" as the mode.
For example:
f = open("path", "a")
Then write to the file and the text should be appended to the end of the file.
That code example works for me:
#!/usr/bin/env python
def write_corpus_to_file(mycorpus, myfile):
with open(myfile, "a") as dstFile:
dstFile.write(mycorpus)
write_corpus_to_file("test", "./test.tmp")
The "with open as" is a convenient way in python to open a file, do something with it while within the block defined by the "with" and let Python handles the rest once you exit it (like, for example, closing the file).
If you want to write the input from the user, you can replace mycorpus with your input (I am not too sure what you want to do from your code snippets).
Note that no carriage return is added by the write method. You probably want to append a "\n" at the end :-)
I'm trying to read in a list of account numbers, then have my program do a search in the appropriate directory for each account number. I want to capture the information from this search, to then split out the file name, date, and time as the output from my program. Currently I'm receiving this error: TypeError: bufsize must be an integer
Here is my code:
def app_files(level):
piv_list_file = raw_input(r"Please enter the full path of the file containing the Pivot ID's you would like to check: ")
piv_id_list = []
proc_out_list = []
input_dir = ''
try:
with open(piv_list_file, 'rbU') as infile:
for line in infile:
line = line.rstrip('\r\n')
piv_id_list.append(line)
except IOError as e:
print 'Unable to open the account number file: %s' % e.strerror
if level == 'p':
input_dir = '[redacted]'
else:
input_dir = '[redacted]'
subprocess.call('cd', input_dir)
for i, e in enumerate(piv_id_list):
proc_out = subprocess.check_output('ls', '-lh', '*CSV*APP*{0}.zip'.format(e))
proc_out_list.append(proc_out)
print(proc_out)
Your subprocess.check_output() function call is wrong. You should provide the complete command as a list (as the first argument). Example -
subprocess.check_output(['ls', '-lh', '*CSV*APP*{0}.zip'.format(e)])
Similar issue with subprocess.call in your code .
I'm trying to get my python file to save numbers into a text file, but it always goes blank when I try it. I've done this many times before but it refuses to work this time.
openfile = 'example'
total = 0.5 #another example
totalstr = str(total)
file = open("%s.txt" % (openfile), "w")
file.write(totalstr)
file.close
"file" is a standard Python type. You want to rename things a bit. I'm also assuming "openfile" should be the string filename you want to use. Both answers so far are correct but putting them together gives:
my_file_name = "myfile"
total = 0.5
my_file_handle = open("%s.txt" %(my_file_name), "w")
my_file_handle.write(str(total))
my_file_handle.close()
file is a keyword in python. So,
print '%s' %(file)
prints
<type 'file'>
You should use:
openfile = 'file'
This works for me:
openfile = "file"
total = 0.5
totalstr = str(total)
file = open("%s.txt" % (openfile), "w")
file.write(totalstr)
file.close()
See if you can spot the changes.