Opening files with an If in Python - if-statement

Profesor1= "Profesor-Materia.txt"
Profesor2= "Profesor-Año.txt"
input ("Seleccione un profesor: ")
if(input=="Profesor1"):
file = open(Profesor1)
data1= file.readlines(1)
print(data1)
else:
file = open(Profesor2)
data = file.readlines(1)
print(data)
So this is my code, I want to open The file: "Profesor-Año" whenever I input anything else than "Profesor1" but it just keeps opening the file "Profesor-Materia" even when I input something like: sadsadsad
Can you help me with this problem?
Ps: I've already tried using if(input==Profesor1)

Your code has quite a few problems. Here is a proper version:
Profesor1 = "Profesor-Materia.txt"
Profesor2 = "Profesor-Año.txt"
in_text = str(input("Seleccione un profesor: "))
if(in_text != 'Profesor1'):
file = open(Profesor2, 'r')
data = file.readlines()
else:
file = open(Profesor1, 'r')
data = file.readlines()
print(data)

Your if statement is just checking that the variable Profesor1 has something in it (see the Python docs on truth value testing), which it does. The user input is being ignored.
You need to change it to something like this:
prof = input ("Seleccione un profesor: ")
if(prof == Profesor1):
# do stuff

Related

How to restore sqlite3 database file programmatically in django

The user wishes to have a database backup and restore functionality through the application. They want to be able to download the database file and upload it to restore the database whenever needed. The problem is that django is already running the current DB file. I wrote the following logic to restore the database.
folder ='./'
if request.method == 'POST':
myfile = request.FILES['file']
fs = FileSystemStorage(location=folder)
if myfile.name.split(".")[1] != "sqlite3":
return JsonResponse({"res":"Please upload a database file."})
if os.path.isfile(os.path.join(folder, "db.sqlite3")):
os.remove(os.path.join(folder, "db.sqlite3"))
filename = fs.save("db.sqlite3", myfile)
file_url = fs.url(filename)
return JsonResponse({"res":file_url})
I get the following error which is rightly justified:
[WinError 32] The process cannot access the file because it is being used by another process
So, is there a way I can achieve this functionality through my application?
I found a better way to create this functionality using a csv. One could store the data from the DB into a csv file and restore it when uploaded. Following is my implementation:
def back_up_done(request):
tables = getTableNames()
sql3_cursor = connection.cursor()
for table in tables:
sql3_cursor.execute(f'SELECT * FROM {table}')
with open('output.csv','a') as out_csv_file:
csv_out = csv.writer(out_csv_file)
for result in sql3_cursor:
csv_out.writerow('Null' if x is None else x for x in result)
csv_out.writerow("|")
BaseDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
csv_path = os.path.join(BaseDir, 'output.csv')
dbfile = File(open(csv_path, "rb"))
response = HttpResponse(dbfile, content_type='application/csv')
response['Content-Disposition'] = 'attachment; filename=%s' % 'backup.csv'
response['Content-Length'] = dbfile.size
os.remove(os.path.join("./", "output.csv"))
return response
def back_up_restore(request):
if request.method == 'POST':
DBfile = request.FILES['file']
cursor = connection.cursor()
if DBfile.name.split(".")[1] != "csv":
messages.add_message(request, messages.ERROR, "Please upload a CSV file.")
return redirect('back-up-db')
tables = getTableNames()
i = 0
deleteColumns()
decoded_file = DBfile.read().decode('utf-8').splitlines()
reader = csv.reader(decoded_file)
for row in reader:
if len(row) != 0:
if(row[0] == "|"):
i += 1
else:
query = f'''Insert into {tables[i]} values({concatRowValues(row)})'''
cursor.execute(query)
connection.close()
messages.add_message(request, messages.SUCCESS, "Data Restored Successfully.")
return redirect('login')
def concatRowValues(row):
data = ''
for i,value in enumerate(row):
if value == "False":
value = '0'
elif value == "True":
value = '1'
if i != len(row) - 1:
data = f'{data}{str(value)},' if value == "Null" else f'{data}\'{str(value)}\','
else:
data = f'{data}{str(value)}' if value == "Null" else f'{data}\'{str(value)}\''
return data
Where getTableNames and concatRowValues are helper functions to get the names of tables and to concatenate column values to form an executable sql statement, respectively. The "|" character is used to mark the end of a table's data.

Python2.7: reading a gzfile content inside a zipfile

Hello I was wondering if there is a way of reading a unformatted file which is stored in gzformat that is stored in zipformat. also this should be done without extracting any file format and outside pluggin than what python 2.7 can provides.
I just want to read entire or line (depending on minimal for memory usage) of the content if there is a bunch of gz in a zipfile then store it in a txt format outside.
My code as of now can read out .log, .gz, .zip also .zip in a zip.
the idea is that it should repeat itself until we get the main file !
Thanks in advance :=)
.zip--->.gz--->unformattedfile
def decompress_file(filepath,type,file=None):
result = {}
if type.lower() == '.log':
if file ==None:
inFile = open(filepath, 'r')
return getLog(inFile)
else:
return getLog(file)
if type.lower() == '.gz':
if file == None:
inFile = gzip.open(filepath, "r")
else:
#content = io.BytesIO(file.read())
with file:
Gz_file= open(file,'r')
for gzFiles in file.namelist():
zFile=file.getinfo(file)
return getLog(zFile)
return getLog(inFile)
print inFile
return getLog(inFile)
if type.lower() == '.zip':
if file == None:
with zip.ZipFile(filepath,'r'):
zFile = zip.ZipFile(filepath)
else:
with zip.ZipFile(file,'r'):
zFile = zip.ZipFile(file)
for f_list in zFile.namelist():
content= io.BytesIO(zFile.read(f_list))
pattern = r'(.+)(?P<file>\.zip|\.gz)'
rgz = re.compile(pattern, re.IGNORECASE)
m = rgz.match(f_list)
if m==None:
type = '.log'
decompress_file(f_list,type,zFile)
else:
decompress_file(f_list,m.group('file').lower(),content)
return result
return result
if __name__ == '__main__':
decompress_file("filepath",'.zip' )

Getting error when using value returned by a function as an input for another function

I am a starter in using python. I am showing a section of the code I was working on. I was trying to communicate python to an arduino using pyserial and blinking a LED. I want to use the value returned by the function send_data to be used as an input for function delay_for_goodant. But when I run the code, I get the error
global name data not defined.
Any suggestions to get rid of this?
def openthedoor(set_accepted_list):
if(((len(set_accepted_list)) >0) & (set_forbidden_list == set()):
print"yes,open the gate"
use_door(1)
else:
print"no,close the gate"
use_door(0)
set_for_comparison = set(set_accepted_list & set_list_ant_id)
list_for_comparison = list(set_for_comparison)
return set_for_comparison,list_for_comparison
def establishing_connection():
print ser.read();
ser.write('1')
last_action = -1
def use_door(activate):
global last_action
if(last_action != activate):
send_data(activate)
last_action = activate
def send_data(data):
if (data ==0):
print "manga"
return True
else:
print "muringa"
return False
def delay_for_goodant(data):
print "thenga"
global ser
try:
if (ser == None):
ser = serial.Serial("COM1",9600,timeout = 0)
print "reconnect"
if send_data(data) is True:
ser.write('0')
time.sleep(0)
incoming_data = ser.readline()
print "python is telling arduino to keep the LED dim"
else:
ser.write('1')
time.sleep(0.7)
incoming_data2 = ser.readline()
print "python is telling the arduino to keep the LED bright"
except IOError:
ser = None
I call these functions in later parts of the code as. Am i doing a mistake here? What i am trying to do here is if data ==0, i want to ser.write('1').
establishing_connection()
set_for_comparison,list_for_comparison = openthedoor(set_accepted_list)
activate = use_door()
data = send_data(activate)
arabica = delay_for_goodant(data)
Also the value inside the function delay_for_goodant is not printed.
This is what i get, when i run the code:
True
muringa
Traceback (most recent call last):
File "door_code_final_calib_dig_2.py", line 352, in <module>
arabica = delay_for_goodant(data)
NameError: name 'data' is not defined

how a program will take an input phrase and synthesise it with pauses according to the wav files

i have tried to take the input phrase and synthesise it with the .wav files given in the folder. if the input phrase has a comma, then it will start after 300ms, if we have a period or question mark, it will start after 400ms.
Started with this code, I don't have an idea how to initiate, join the phrase and play the wav files.
parser.add_argument('--play', '-a', action="store", default=False)
args = parser.parse_args()
class Synthesis(object):
def __init__(self, wav_folder):
self.phones = {}
self.get_wavs(wav_folder)
def get_wavs(self, wav_folder):
for root, dirs, files in os.walk(wav_folder, topdown=False):
for file in files:
filesplit = file.split('.')
filename = filesplit[0]
self.phones[filename] = AS.Audio()
self.phones[filename].load(root + '/' + file)
def punctuation(phrase):
concate_punc = []
for word in phrase:
phn_ex= re.match(r'[a-z]+\|,|[.]|!|[?]', word)
phone_exception = phn_ex.group(0)
print phone_exception
if __name__ == "__main__":
S = Synthesis(wav_folder=args.phones)
output = AS.Audio(rate=48000)

Need the Groovy way to do partial file substitutions

I have a file that I need to modify. The part I need to modify (not the entire file), is similar to the properties shown below. The problem is that I only need to replace part of the "value", the "ConfigurablePart" if you will. I receive this file so can not control it's format.
alpha.beta.gamma.1 = constantPart1ConfigurablePart1
alpha.beta.gamma.2 = constantPart2ConfigurablePart2
alpha.beta.gamma.3 = constantPart3ConfigurablePart3
I made this work this way, though I know it is really bad!
def updateFile(String pattern, String updatedValue) {
def myFile = new File(".", "inputs/fileInherited.txt")
StringBuffer updatedFileText = new StringBuffer()
def ls = System.getProperty('line.separator')
myFile.eachLine{ line ->
def regex = Pattern.compile(/$pattern/)
def m = (line =~ regex)
if (m.matches()) {
def buf = new StringBuffer(line)
buf.replace(m.start(1), m.end(1), updatedValue)
line = buf.toString()
}
println line
updatedFileText.append(line).append(ls)
}
myFile.write(updatedFileText.toString())
}
The passed in pattern is required to contain a group that is substituted in the StringBuffer. Does anyone know how this should really be done in Groovy?
EDIT -- to define the expected output
The file that contains the example lines needs to be updated such that the "ConfigurablePart" of each line is replaced with the updated text provided. For my ugly solution, I would need to call the method 3 times, once to replace ConfigurablePart1, once for ConfigurablePart2, and finally for ConfigurablePart3. There is likely a better approach to this too!!!
*UPDATED -- Answer that did what I really needed *
In case others ever hit a similar issue, the groovy code improvements I asked about are best reflected in the accepted answer. However, for my problem that did not quite solve my issues. As I needed to substitute only a portion of the matched lines, I needed to use back-references and groups. The only way I could make this work was to define a three-part regEx like:
(.*)(matchThisPart)(.*)
Once that was done, I was able to use:
it.replaceAdd(~/$pattern/, "\$1$replacement\$3")
Thanks to both replies - each helped me out a lot!
It can be made more verbose with the use of closure as args. Here is how this can be done:
//abc.txt
abc.item.1 = someDummyItem1
abc.item.2 = someDummyItem2
abc.item.3 = someDummyItem3
alpha.beta.gamma.1 = constantPart1ConfigurablePart1
alpha.beta.gamma.2 = constantPart2ConfigurablePart2
alpha.beta.gamma.3 = constantPart3ConfigurablePart3
abc.item.4 = someDummyItem4
abc.item.5 = someDummyItem5
abc.item.6 = someDummyItem6
Groovy Code:-
//Replace the pattern in file and write to file sequentially.
def replacePatternInFile(file, Closure replaceText) {
file.write(replaceText(file.text))
}
def file = new File('abc.txt')
def patternToFind = ~/ConfigurablePart/
def patternToReplace = 'NewItem'
//Call the method
replacePatternInFile(file){
it.replaceAll(patternToFind, patternToReplace)
}
println file.getText()
//Prints:
abc.item.1 = someDummyItem1
abc.item.2 = someDummyItem2
abc.item.3 = someDummyItem3
alpha.beta.gamma.1 = constantPart1NewItem1
alpha.beta.gamma.2 = constantPart2NewItem2
alpha.beta.gamma.3 = constantPart3NewItem3
abc.item.4 = someDummyItem4
abc.item.5 = someDummyItem5
abc.item.6 = someDummyItem6
Confirm file abc.txt. I have not used the method updateFile() as done by you, but you can very well parameterize as below:-
def updateFile(file, patternToFind, patternToReplace){
replacePatternInFile(file){
it.replaceAll(patternToFind, patternToReplace)
}
}
For a quick answer I'd just go this route:
patterns = [pattern1 : constantPart1ConfigurablePart1,
pattern2 : constantPart2ConfigurablePart2,
pattern3 : constantPart3ConfigurablePart3]
def myFile = new File(".", "inputs/fileInherited.txt")
StringBuffer updatedFileText = new StringBuffer()
def ls = System.getProperty('line.separator')
myFile.eachLine{ line ->
patterns.each { pattern, replacement ->
line = line.replaceAll(pattern, replacement)
}
println line
updatedFileText.append(line).append(ls)
}
myFile.write(updatedFileText.toString())