Writing to a file won't work - python

Even with the most basic of code, my .txt file is coming out empty, and I can't understand why. I'm running this subroutine in python 3 to gather information from the user. When I open the .txt file in both notepad and N++, I get an empty file.
Here's my code :
def Setup():
fw = open('AutoLoader.txt', 'a')
x = True
while x == True:
print("Enter new location to enter")
new_entry = str(input('Start with \'web\' if it\'s a web page\n'))
fw.write(new_entry)
y = input('New Data? Y/N\n')
if y == 'N' or y == 'n':
fw.close
break
fw.close
Start()

Try replacing fw.close with fw.close()

It's working on python 3.4
def Setup():
fw = open('AutoLoader3.4.txt', 'a+')
x = True
while x == True:
print("Enter new location to enter")
new_entry = str(input('Start with \'web\' if it\'s a web page\n'))
fw.write(new_entry)
y = input('New Data? Y/N\n')
if y == 'N' or y == 'n':
fw.close()
break
fw.close()
Setup()

Not knowing what Start() does, it must be ignored in answers, so far...
I wouldn't bother to close the file myself, but let a with statement do the job properly.
Following script works at least:
#!/usr/bin/env python3
def Setup():
with open('AutoLoader.txt', 'a') as fw:
while True:
print("Enter new location to enter")
new_entry = str(input("Start with 'web' if it's a web page\n"))
fw.write(new_entry + "\n")
y = input('New Data? Y/N\n')
if y in ['N', 'n']:
break
#Start()
Setup()
See:
nico#ometeotl:~/temp$ ./test_script3.py
Enter new location to enter
Start with 'web' if it's a web page
First user's entry
New Data? Y/N
N
nico#ometeotl:~/temp$ ./test_script3.py
Enter new location to enter
Start with 'web' if it's a web page
Another user's entry
New Data? Y/N
N
nico#ometeotl:~/temp$ cat AutoLoader.txt
First user's entry
Another user's entry
nico#ometeotl:~/temp$
Also note that a possibly missing AutoLoader.txt at start would be created automatically.

Related

scan a directory created a selected list of scripts, put in a list and execute them one by one

I am very new to sw coding needing some help. Thank You!
I have a script that scan a path for .py files and display it it in menu format using enumerates
Ask user to select file/files they want to run and put them in a list
And start ran those file from this list one by one
My issue is that it only ran the the fist selected file from the user selected list. Here is my simple code.
import os
import sys
choice_1 = ''
run_list = []
while choice_1 != 'q':
print("\nPlease select desire test case: ")
items = os.listdir("C:/Users/tonp\PycharmProjects/untitled1")
fileList = [name for name in items if name.endswith(".py")]
for cnt, fileName in enumerate(fileList, 0):
sys.stdout.write("[%d] %s\n\r" % (cnt, fileName))
choice = int(input("Select from [1-%s]: " % cnt))
choice_1 = input("Press any key to add more case or q to start running testsuite ")
run_list.append(fileList[choice])
print("These are the case/s you have selected so far :")
print(run_list)
selected_files = run_list
for x in run_list:
exec(open(c).read())
You may need to use importlib.
Check this link for an answer that might help you in this direction:
Exit an imported module without exiting the main program - Python
To allow the user to exit as needed you can do something like this inside the while True:
sys.stdout.write('Type file name (Enter to exit): ')
try:
sys.stdout.flush()
filename = sys.stdin.readline().strip()
if filename == '':
print('Exiting...')
break()
except:
exit()

How to open and read a file in python while it's an subfolder?

I have created a program where I have two text files: "places.txt" and "verbs.txt" and It asks the user to choose between these two files. After they've chosen it quizzes the user on the English translation from the Spanish word and returns the correct answer once the user has completed their "test". However the program runs smoothly if the text files are free in the folder for python I have created on my Mac but once I put these files and the .py file in a subfolder it says files can't be found. I want to share this .py file along with the text files but would there be a way I can fix this error?
def CreateQuiz(i):
# here i'm creating the keys and values of the "flashcards"
f = open(fileList[i],'r') # using the read function for both files
EngSpanVocab= {} # this converts the lists in the text files to dictionaries
for line in f:
#here this trims the empty lines in the text files
line = line.strip().split(':')
engWord = line[0]
spanWord = line[1].split(',')
EngSpanVocab[engWord] = spanWord
placeList = list(EngSpanVocab.keys())
while True:
num = input('How many words in your quiz? ==>')
try:
num = int(num)
if num <= 0 or num >= 10:
print('Number must be greater than zero and less than or equal to 10')
else:
correct = 0
#this takes the user input
for j in range(num):
val = random.choice(placeList)
spa = input('Enter a valid spanish phrase for '+val+'\n'+'==> ')
if spa in EngSpanVocab[val]:
correct = correct+1
if len(EngSpanVocab[val]) == 1:
#if answers are correct the program returns value
print('Correct. Good work\n')
else:
data = EngSpanVocab[val].copy()
data.remove(spa)
print('Correct. You could also have chosen',*data,'\n')
else:
print('Incorrect, right answer was',*EngSpanVocab[val])
#gives back the user answer as a percentage right out of a 100%
prob = round((correct/num)*100,2)
print('\nYou got '+str(correct)+' out of '+str(num)+', which is '+str(prob)+'%'+'\n')
break
except:
print('You must enter an integer')
def write(wrongDict, targetFile):
# Open
writeFile = open(targetFile, 'w')
# Write entry
for key in wrongDict.keys():
## Key
writeFile.write(key)
writeFile.write(':')
## Value(s)
for value in wrongDict[key]:
# If key has multiple values or user chooses more than 1 word to be quizzed on
if value == wrongDict[key][(len(wrongDict[key])) - 1]:
writeFile.write(value)
else:
writeFile.write('%s,'%value)
writeFile.write('\n')
# Close
writeFile.close()
print ('Incorrect answers written to',targetFile,'.')
def writewrong(wringDict):
#this is for the file that will be written in
string_1= input("Filename (defaults to \'wrong.txt\'):")
if string_1== ' ':
target_file='wrong.txt'
else:
target_file= string_1
# this checs if it already exists and if it does then it overwrites what was on it previously
if os.path.isfile(target)==True:
while True:
string_2=input("File already exists. Overwrite? (Yes or No):")
if string_2== ' ':
write(wrongDict, target_file)
break
else:
over_list=[]
for i in string_1:
if i.isalpha(): ovrList.append(i)
ovr = ''.join(ovrList)
ovr = ovr.lower()
if ovr.isalpha() == True:
#### Evaluate answer
if ovr[0] == 'y':
write(wrongDict, target)
break
elif ovr[0] == 'n':
break
else:
print ('Invalid input.\n')
### If not, create
else:
write(wrongDict, target)
def MainMenu():
## # this is just the standad menu when you first run the program
if len(fileList) == 0:
print('Error! No file found')
else:
print( "Vocabulary Program:\nChoose a file with the proper number or press Q to quit" )
print(str(1) ,"Places.txt")
print(str(2) ,"Verbs.txt")
while True:
#this takes the user input given and opens up the right text file depending on what the user wants
MainMenu()
userChoice = input('==> ')
if userChoice == '1':
data = open("places.txt",'r')
CreateQuiz(0)
elif userChoice == '2':
data = open("verbs.txt",'r')
CreateQuiz(1)
elif userChoice == 'Q':
break
else:
print('Choose a Valid Option!!\n')
break
You are probably not running the script from within the new folder, so it tries to load the files from the directory from where you run the script.
Try setting the directory:
import os
directory = os.path.dirname(os.path.abspath(__file__))
data = open(directory + "/places.txt",'r')

python .exe file won't open/run

I wrote a python file in visual studio code with anaconda as the interpreter. I used pyinstaller to turn the file into an exe but when I try to open the exe a cmd window flashes open for a second and then closes. I don't know why it won't open. My program is supposed to read and print out specific data requested by the user from a HDF5 file and it does exactly that in visual studio code. I really just need a way to make it able to be run by someone on a different computer with python not installed.
Here is my entire code I know its probably bad because I don't have much python experience, but it works in visual studio code:
import numpy as np
import h5py
print ("Make sure to move the HDF file to the folder where this program is located.")
valid = "valid"
#gets the file name and checks if file exists
while valid == "valid":
filename = input("\nwhat is the name of the HDF file including the .hdf: ")
try:
with h5py.File(filename,"r") as hdf:
path = hdf.get("/Results/Unsteady/Output/Output Blocks/Base Output/Unsteady Time Series/2D Flow Areas/Flow Area")
break
except IOError:
print ("File not found")
#opens file
with h5py.File(filename,"r") as hdf:
#navigates to file location
path = hdf.get("/Results/Unsteady/Output/Output Blocks/Base Output/Unsteady Time Series/2D Flow Areas/Flow Area")
path_items = list(path.items())
#keeps running until user tells it to stop
run = "y"
while run == "y" or run == "Y" or run == "yes" or run == "Yes":
#user input
while valid == "valid":
choice = input("\nWhich file would you like to get data from? Depth, Face Shear stress, Face Velocity, or Water Surface: ")
choice = choice.lower()
if choice == "depth" or choice == "face shear stress" or choice == "face velocity" or choice == "water surface":
break
else:
print ("Invalid")
#checks the user input then converts the data set into a numpy array
if choice == "depth":
dataset = np.array(path.get("Depth"))
if choice == "face shear stress":
dataset = np.array(path.get("Face Shear Stress"))
if choice == "face velocity":
dataset = np.array(path.get("Face Velocity"))
if choice == "water surface":
dataset = np.array(path.get("Water Surface"))
#gets the shape/size of the dataset
shape = str(dataset.shape)
shape = shape.replace("(","")
shape = shape.replace(")","")
shape = shape.split(",")
timeAmount = shape[0]
pointAmount = shape[1]
timeAmount = int(timeAmount)
pointAmount = int(pointAmount)
timeAmount -= 1
pointAmount -= 1
print ("\nThis data set has",timeAmount,"time values and",pointAmount,"data values.")
#user input
while valid == "valid":
time = input("\nEnter a single time step: ")
try:
int(time)
break
except ValueError:
print ("Invalid")
time = int(time)
while valid == "valid":
minR = input("\nEnter the first (smaller) value in a range of cell locations: ")
try:
int(minR)
break
except ValueError:
print ("Invalid")
minR = int(minR)
while valid == "valid":
maxR = input("\nEnter the second (larger) value in a range of cell locations: ")
try:
int(maxR)
break
except ValueError:
print ("Invalid")
maxR = int(maxR)
#calculates all the numbers in the range between the two numbers
rangeL = []
while minR != maxR:
rangeL.append(minR)
minR += 1
rangeL.append(maxR)
#prints the value at each point
count = 0
for x in range(len(rangeL)):
tempN = rangeL[count]
tempV = dataset[time,rangeL[count]]
print (str(tempN) + "," + str(tempV))
count += 1
#asks the user if they want to get more data
run = input("\nWould you like to enter more parameters to get more/different data? (y/n): ")
if run == "y" or run == "Y" or run == "yes" or run == "Yes":
pass
else:
print ("Goodbye")
break
Probably because you have a code with just a few outputs. That means that the programm executes those lines really fast and eventually closes. Request for an input at the end of your code. That should make the program to stay open.
It worked for me. I used pyinstaller with command: pyinstaller -F file_name.py. It works. Doesn't close fast and asks for the input also.

TypeError 'str' objects is not callable - Python

I'm completely new to Python and i'm trying to write a program that essentially works as an alarm clock. I prompt the user for a specific time to set the alarm to and then when that time occurs, a youtube video taken from a list of youtube videos in a txt file will play. However, I'm not quite sure why i'm getting this error, as i'm still largely unfamiliar with python syntax. Here's my code:
import time
def addVideo():
videoToAdd = raw_input("Enter the url of the video to add: ")
with open('alarmVideos.txt', 'w') as f:
f.write(videoToAdd + '\n')
alarmTime = raw_input("When would you like to set your alarm to?: \nPlease use this format: 01:00\n")
localTime = time.strftime("%H:%M")
addVideo = raw_input("Would you like to add a video to your list? (y/n): \n")
if addVideo == 'y' or addVideo == 'n':
addVideo()
print "Your alarm is set to:", alarmTime
I'm getting this error:
Traceback (most recent call last):
File "C:\Users\bkrause080\Desktop\Free Time Projects\LearningPythonProjects\alarmClock.py", line 15, in <module>
addVideo()
TypeError: 'str' object is not callable
If it helps this error occurs after the user enters y/n to whether not not they want to add a video to their list. Thanks for any help!
Problem is since you named both the function name and variable with the same name(addVideo),Python 'confuses' the function and variable.Rename any one of them:
import time
def addVideo():
videoToAdd = raw_input("Enter the url of the video to add: ")
with open('alarmVideos.txt', 'w') as f:
f.write(videoToAdd + '\n')
alarmTime =raw_input("When would you like to set your alarm to?: \nPlease use this format: 01:00\n")
localTime = time.strftime("%H:%M")
add_Video = raw_input("Would you like to add a video to your list? (y/n): \n")
if add_Video == 'y' or add_Video == 'n':
addVideo()
print( "Your alarm is set to:", alarmTime)
Output:
When would you like to set your alarm to?:
Please use this format: 01:00
Would you like to add a video to your list? (y/n):
n
Enter the url of the video to add: grg
Your alarm is set to:
You are overwriting the function addVideo() with a string: addVideo = raw_input("Would you like ...")
You need to rename the function or the varaible.
addVideoResult = raw_input("Would...")
if addVideoResult == 'y' or addVideoResult == 'n':
addVideo()
You need a different name reference for raw_input("Would you like to add a video to your list? (y/n): \n") since you are overriding the function:
run = raw_input("Would you like to add a video to your list? (y/n): \n")
if run == 'y' or run == 'n':
addVideo()

How to write to a text file using iteration?

My code does not write to a file, what am I doing wrong? I am trying to program to continue to ask for products until the user does not enter a product code. I want all products to be saved in the file.
store_file = open("Database.txt", "w")
NewProduct = ""
while NewProduct != False:
contine = input("Press 1 to enter a new product press 2 to leave: ")
if contine == "1":
print("Enter your product information")
information = []
product = input("What's the product code: ")
information.append(product)
description = input("Give a description of the product: ")
information.append(description)
price = input("Enter price of product: ")
information.append(price)
information = str(information)
clean = information.replace("]","").replace("[","").replace(",","").replace("'","")
store_file.write(clean)
elif contine == "2":
NewProduct = False
else:
print("Your input is invalid")
store_file.close
I got the program working with the following adjustments. See comments for explanations:
store_file = open("Database.txt", "w")
NewProduct = ""
while NewProduct != False:
continue = raw_input("Press 1 to enter a new product press 2 to leave: ")
#Changed to raw_input because input was reading in an integer for 1 rather than a
#string like you have set up. This could be specific to my IDE
if continue == "1":
print("Enter your product information")
information = []
product = raw_input("What's the product code: ")
information.append(product)
description = raw_input("Give a description of the product: ")
information.append(description)
price = raw_input("Enter price of product: ")
information.append(price)
information = str(information)
clean = information.replace("]","").replace("[","").replace(",","").replace("'","")
store_file.write(clean + "\n")
#Added a line break at the end of each file write
elif contine == "2":
NewProduct = False
else:
print("Your input is invalid")
store_file.close() #Added parentheses to call the close function
I'm assuming the problem here is that you're using Python 2, and input isn't doing what you think it does. In Python 2, input evals the input as if it were Python source code, so if someone enters 2, it's going to return the int value 2, not "2". In Python 2, you want to use raw_input, always (eval-ing random user input not being secure/reliable).
Also, while on CPython (the reference interpreter) files tend to naturally close themselves when they go out of scope, you made an effort to close, but forgot to actually call the close method; store_file.close looks up the method without calling it, store_file.close() would actually close it. Of course, explicit close is usually the wrong approach; you should use a with statement to avoid the possibility of forgetting to close (or of an exception skipping the close). You can replace:
store_file = open("Database.txt", "w")
...
store_file.close()
with:
with open("Database.txt", "w") as store_file:
... do all your work that writes to the file indented within the with block ...
... When you dedent from the with block, the file is guaranteed to be closed ...
There are other issues though. What you're doing with:
information = str(information)
information = information.replace("]","").replace("[","").replace(",","").replace("'","")
is terrible. I'm 99% sure what you really wanted was to just join the inputs with spaces. If you switch all your input calls to raw_input (only on Python 2, on Python 3, input is like raw_input on Python 2), then your list is a list of str, and you can just join them together instead of trying to stringify the list itself, then remove all the list-y bits. You can replace both lines above with just:
information = ' '.join(information)

Categories