Is it possible to write a code in python that saves and writes files automatically?
How I want the code to work:
The user opens the program. The program asks for an input, lets say it asks for the users name. User inputs his name. The program then takes that name and writes it in an external file and saves. The user then closes the program. Next time the program is opened it imports the external file, thus knowing the name of the user.
Yes of corse this are here a same introduction with some lines
import os
def write_to_file(name):
text_file = open("%s.txt"% name , "w")
text_file.write("%s" % name)
text_file.close()
def check_exists(name):
if os.path.exists("./"+name+".txt"):
print "File found!"
else:
write_to_file(name)
def input_name():
return(raw_input("input name: "))
check_exists(input_name())
Related
I'm currently working with a python script that has the following code. It opens a file that has JSON text and determines a value from that.
browseFiles()
def browseFiles():
global fileName
fileName = filedialog.askopenfilename(title = "Select a File", filetypes = (("All Files","*.*")))
# Open the File in Read Mode
fileFile = open(fileName, "r")
# Read the file
fileContent = fileFile.read()
# Render the JSON
fileJSON = json.loads(fileContent)
# Determine the ID
myID = fileJSON["key"]
# Update the Status
windowRoot.title(myID)
... remaining code
fileFile.close()
However, it is less convenient to open the program every time, and then navigate to it.
Windows has an 'Open With' feature in File Explorer where we can right-click a file and open it with apps such as Word, etc.
How to implement this in a Python script? Should I consider creating a .exe of this script first, and if yes then which library would be most suitable for this? (Considering it is a very small and simple utility)
Some extra information that is probably unwanted: I'm using Tkinter for the GUI.
(By the way, if this question already exists on StackOverFlow or any other website, then please comment the link instead of just marking it as duplicate. I tried searching a lot and couldn't find anything)
Regards,
Vivaan.
simple example:
import sys
try:
#if "open with" has been used
print(sys.argv[1])
except:
#do nothing
pass
usage example:
import sys
from tkinter import filedialog
filetypes = (('Text files', '*.txt'),('All files', '*.*'))
#if filename is not specified, ask for a file
def openfile(filename = ''):
#print contents of file
if filename == '':
filename = filedialog.askopenfilename(title='Open A File',filetypes=filetypes)
with open(filename,'r', encoding="utf-8") as file:
read = file.read()
print(read)
try:
#if "open with" has been used
openfile(filename = sys.argv[1])
except:
#ask for a file
openfile()
then compile it to exe with nuitka (or whatever tool you use),
and try it.
or (for testing, without having to compile it every time you make a change):
make a .bat file
#echo off
py program.py %*
pause
Then every time you want to run it,
you open with that file.
what you need is added new item into right click context menu.
You can take sample registry code below, modify the path to your py script C:\your_script.py and save it as anything end with .reg extension then double click to execute this registry file.
after that, you should see open with my_py when u right click on the target file
from your py script side, replace the filedialog code with fileName = sys.argv[1]
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\*\shell\open with my_py\command]
#="python C:\\your_script.py %1"
*** Please be cautious with the registry code as wrong registry hack can be troublesome
refer this for manually modify the registry
Found another question with answers that helped me. Posting this for other people who might find this question.
answer from Roy Cai:
My approach is to use a redirect .bat file containing python someprogram.py %1. The %1 passes the file path into the python script which can be accessed with
from sys import argv
argv[1]
I'm writing a program, and I want to make users type feedback in the form of a prompt function in pyautogui. Is there any way I can record the text entered here; preferably in a text file?
Their docs say that pyautogui.prompt returns the text input or None if users hit cancel. Writing the text input to a file can be done like this:
import pyautogui as py
text = py.prompt(text='Do you like apples?', title='Question', default='YES')
with open('file.txt', 'w') as file:
file.writelines(text)
More easily you can just save the calling of prompt function to a variable,like:
import pyautogui
text = pyautogui.prompt(text='Do you like apples?', title='Question', default='YES')
#now you will have the text entered in the prompt saved in 'text' variable
print(text)
This question already has answers here:
.write not working in Python
(5 answers)
Closed 6 years ago.
So i am writing a program and i made a function which stores user data in a txt file.It is like a simple registration function.The user gives the username and password to store.Problem is i can't store user input in the file.
My code is :
def reguser(): #Function name.
fwu = open('user.txt','w') #create or open user.txt file.
user = input("Username: ") #takes the user input.e.g what username to register
fwu.write(user) #this command should write input into the file
fwp = open('pass.txt','w') #create or open pass.txt file.
pas = input ("Password: ") #takes user input e.g what password to register
fwp.write(pas) #write the password into the file
print ("To check for registraion completion, please login.")
askuser()
So what i get is two text files user and pass but they are empty.
What am i doing wrong??
and please do not tell me to use modules for registraion.
Regards ali7112001
You didn't fwu.close() or fwp.close() (you didn't save it). Also a quick look up next time would save you some time. .write not working in Python
Please try with raw_input() instead of input()
Also please close() the files.
I have a python program that just needs to save one line of text (a path to a specific folder on the computer).
I've got it working to store it in a text file and read from it; however, I'd much prefer a solution where the python file is the only one.
And so, I ask: is there any way to save text in a python program even after its closed, without any new files being created?
EDIT: I'm using py2exe to make the program an .exe file afterwards: maybe the file could be stored in there, and so it's as though there is no text file?
You can save the file name in the Python script and modify it in the script itself, if you like. For example:
import re,sys
savefile = "widget.txt"
x = input("Save file name?:")
lines = list(open(sys.argv[0]))
out = open(sys.argv[0],"w")
for line in lines:
if re.match("^savefile",line):
line = 'savefile = "' + x + '"\n'
out.write(line)
This script reads itself into a list then opens itself again for writing and amends the line in which savefile is set. Each time the script is run, the change to the value of savefile will be persistent.
I wouldn't necessarily recommend this sort of self-modifying code as good practice, but I think this may be what you're looking for.
Seems like what you want to do would better be solved using the Windows Registry - I am assuming that since you mentioned you'll be creating an exe from your script.
This following snippet tries to read a string from the registry and if it doesn't find it (such as when the program is started for the first time) it will create this string. No files, no mess... except that there will be a registry entry lying around. If you remove the software from the computer, you should also remove the key from the registry. Also be sure to change the MyCompany and MyProgram and My String designators to something more meaningful.
See the Python _winreg API for details.
import _winreg as wr
key_location = r'Software\MyCompany\MyProgram'
try:
key = wr.OpenKey(wr.HKEY_CURRENT_USER, key_location, 0, wr.KEY_ALL_ACCESS)
value = wr.QueryValueEx(key, 'My String')
print('Found value:', value)
except:
print('Creating value.')
key = wr.CreateKey(wr.HKEY_CURRENT_USER, key_location)
wr.SetValueEx(key, 'My String', 0, wr.REG_SZ, 'This is what I want to save!')
wr.CloseKey(key)
Note that the _winreg module is called winreg in Python 3.
Why don't you just put it at the beginning of the code. E.g. start your code:
import ... #import statements should always go first
path = 'what you want to save'
And now you have path saved as a string
I'm trying to write a script that asks for an input file and then runs some command on it. when I run the script it askes me for filename and when I give the file (e.g example.bam) then I get this error:
NameError: name 'example.bam' is not defined
I tried many things but I couldn't fix it. Can someone tell me what is wrong?
This is my comand:
from subprocess import call
filename = input ("filename: ");
with open (filename, "r") as a:
for command in ("samtools tview 'a' /chicken/chick_build2.1_unmasked.fa",):
call(command, shell=True)
This is a short version of my command: it has to do much more stuff. I'm also thinking to input 4-6 files at same time (perhaps this information is helpful to clarify my intentions).
input is equivalent to eval(raw_input(prompt)). So what your script currently tries to do is interpret your input ("example", in your case), and execute as if it were a statement in your script. For user input (and might I simply say "for any input" -- unless you know what you're doing), always use the raw_input function.
So, to solve it, replace input with raw_input:
filename = raw_input("filename: ")