So, I'm using TKinter with Python to try and take an input from the user and write that into a seperate file for use later, but I can't seem to get it to work. Having looked over other questions and adapting some parts of my code in accordance to their answers, I still can't get it to work.
Here's the full code:
import tkinter
def write_File (text_File):
file = open("users.txt", "a")
user_Input = str(file)
file.write(user_Input).get()
text_File.insert(INSERT, file.read())
file.close()
screen = tkinter.Tk()
the_input = tkinter.Entry(screen)
the_input.grid(row=1, column=1)
button_Write = tkinter.Button(screen, text = "Send to file:", command = lambda: write_File(the_input)).grid(row=10, column=1)
screen.mainloop()
The Error I'm given in the console, after pressing the button, says:
File "[file directory]", line 9, in write_File
file.write(user_Input).get()
AttributeError: 'int' object has no attribute 'get'
Anyone able to offer any assistance?
So I'm not entirely certain what resources you were using to create write_File, but there were a few errors. I've fixed them in the below code, with comments to explain what I've changed and why.
import tkinter
def write_File (text_File):
file = open("users.txt", "a")
#The object text_File is a tkinter.Entry object, so we will get
# the user input by calling the get method on that object.
user_Input = text_File.get()
#Here we now directly write the user input to the file that has been
# opened, I'm not sure you were previously doing with writing the
# string version of the file, but this appears to achieve what you
# desire.
file.write(user_Input)
file.close()
screen = tkinter.Tk()
the_input = tkinter.Entry(screen)
the_input.grid(row=1, column=1)
button_Write = tkinter.Button(screen, text = "Send to file:", command = lambda: write_File(the_input)).grid(row=10, column=1)
screen.mainloop()
Another thing is that depending on the version of Python you're using, instead of using file = open(...) and then file.close() at the end of the method, you could instead use the with open(...) as file: construct which will automatically close the file at the end of the scope.
Your function should look something like this:
def write_file (user_input): # naming convention for functions in python is__like_this
file = open("users.txt", "a") # 'a' stands for 'append'
file.write(user_input)
file.close()
or even better using context manager
def write_File (user_input):
with open('users.txt', 'a') as file:
file.write(user_input)
Related
I'm new to python and am struggling to figure out how to load a line from a file into a string so I can parse it and act on it. The input text file is a script for a video that will create Amazon Polly mp3 files, based on the text in the file.
The file uses the first character as either an 'A:'(action, ignore),'F:'(filename),'T:'(text for Polly),or '#' (comment, ignore) then followed by string text, For example:
#This example says that the author should move the cursor, then the corresponding Audio
#created from Polly ("Move the cursor to the specified location") is dumped into Move_Cursor.mp3
A:Move the cursor
T:Move the cursor to the specified location
F:Move_Cursor.mp3
#end of example
I've been trying to use the read or readline, but I can't figure out how to take the value returned by those to create a string so I can parse it.
script_file = open(input("Enter the script filename: "),'r')
lines = script_file.readlines()
cnt = 0
for line in lines:
eol = len(line)
print ("line length is: ",eol)
action = line.read #<<THIS IS WHERE I'M HAVING A TYPE ISSUE
print ("action is ",action)
print ("string is ",line)
script_file.close()
Thank you!!!!
Here is a possible solution:
filename = input('Enter the script filename: ')
actions = {'#': 'comment', 'A': 'action', 'T': 'text for polly', 'F': 'filename'}
with open(filename, 'r') as file:
for line in file:
line = line.strip()
lof = len(line)
action = actions.get(line[0])
text = line[1:].lstrip(':')
print(
f'Length of line: {lof}\n'
f' Action: {action}\n'
f' Text: {text}\n'
)
Also I would suggest that for choosing files you use the built-in tkinter module which has a function for displaying the file chooser (it will limit human error in typing out the correct filename):
from tkinter import Tk, filedialog
Tk().withdraw()
filename = filedialog.askopenfilename()
Or just skip the filename part:
from tkinter import Tk, filedialog
Tk().withdraw()
with filedialog.askopenfile(mode='r') as file:
For those of you interested. Being new to python, I got sloppy with my spaces and tabs. My issue with the code, even though it was pointing to a syntax error on a line that should have passed, was that I was mixing spaces and tabs in my indentation, so it lost it's mind. BUT, THANK YOU for everyone that answered, as it did help me figure out a better way of doing what I was trying to do, and of course, I did find a missing ':' also.
You can check the first character of every line with:
action = line[0]
I have created a Entry box:
I have created a text file:
save_file.close()
However the data being entered is not saving to the text file. This is being saved:
Accounts
<bound method Entry.get of <tkinter.Entry object .!entry>><bound method Entry.get of <tkinter.Entry object .!entry2>>
Any idea on how to fix this?
You need to call the get method.
Change
save_file.write(str(username_input_box.get))
to
save_file.write(str(username_input_box.get()))
As you are having trouble, I have written out a very basic version of your program which I have tested and it works. It writes the "Accounts" text to the file and when the button is pressed, it writes the content of the entry field to the file too. If you code still isn't working, perhaps you'll need to post a more complete and executable example of your code
from tkinter import *
def creating_text_file():
save_file = open("Accounts.txt", "a")
title = "Accounts"
line = "\n"
save_file.write(title)
save_file.write(line)
save_file.close()
def apending_to_text_file():
save_file = open("Accounts.txt", "a")
save_file.write(str(username_input_box.get()))
save_file.write("\n")
save_file.close()
root = Tk()
username_input_box = Entry(root, width=30)
username_input_box.grid()
btn = Button(root,text="Press Me",command=apending_to_text_file)
btn.grid()
creating_text_file()
root.mainloop()
As an improvement, I'd use the context managers to open/close your file. They look like this
with open("Accounts.txt", "a") as save_file:
save_file.write("Some random text")
#No need to close the file as the context manager does this for you
I am writing a Python module which will read and analyze an input file for a specialized software program. I want the user to be able to analyze whichever input file they choose. So far I've tried 2 methods to get the file name:
Method 1:
filename = input('File to be analyzed: ')
Pro: simplest method
Con: difficult for user to type long file path every time
Method 2:
Put a file called path.txt in the same directory as the Python module and the user can store the filename there.
import os
pathtxt_dir = os.path.dirname(os.path.realpath(__file__))
pathtxt_fullpath = os.path.join(pathtxt_dir, 'path.txt')
try:
fo = open(pathtxt_fullpath, 'r')
lines = fo.readlines()
fo.close()
except IOError:
raise Exception('path.txt cannot be opened')
filename = lines[0].rstrip().lstrip() # input file
Pro: Coworkers are familiar with this approach since it is similar to previous programs they have used.
Con: It seems like an unnecessarily complicated way to get user input
Question:
Is there a canonical Python method for getting long and repetitive user inputs, like this filename? Also, is there another useful method that I have not considered?
You can use tkinter to open a GUI for them to select the file. That way they don't have to type it out every time.
import tkinter as tk
from tkinter import filedialog as fd
import os
def getfile(title='Choose files', sformat='.*'):
root = tk.Tk()
root.lift()
# d and f are whatever default directory and filename
try:
f = fd.askopenfilename(parent=root, title=title, filetypes=[('', sformat)], initialdir=d, initialfile=f)
root.withdraw()
return f
except:
# print(title + ': error - no file exists')
return ''
I'm currently having some trouble with checking if things are written down in my textfile.
In my code, I check if "1" is in my storefile.txt file. If "1" isn't in the textfile, signalling that the user has opened the code for the first time, Tkinter asks for the user's name and puts in "1" (signalling that the user has opened the code before). If not, Tkinter says "Welcome back," and the user's inputted name.
However, even after I open the code after the first time, the code acts like "1" isn't even in the storefile, even though it is. The code asks for my name and prints "1" again, so I end up having more than 1 "1"s in my storefile and never reach to the "Welcome back," [name] stage.
import tkinter as tk
from time import time
from tkinter import *
root = Tk()
#FUNCTION FOR LABELS (not necessary but it condenses the code)
def label(a):
Label(root,text=a,font=("System",15,"bold"),fg="steelblue").pack()
#THIS IS FOR EXTRACTING SPECIFIC DATA FROM THE TEXTFILE
lines = [] #Declare an empty list named "lines"
def specify(x):
with open ('storefile.txt', 'rt+') as in_file: #Open file lorem.txt for reading of text data.
for line in in_file: #For each line of text store in a string variable named "line", and
lines.append(line) #add that line to our list of lines.
label(lines[x]) #print the list object.
#[x] allows us to print whatever line we want.
#############################
#THIS IS FOR THE 'ENTER NAME' BUTTON TO STORE NAMES
def store():
user_entry = distance_text_box.get()
f=open("storefile.txt", "a")
f.write (str(user_entry))
f.close()
#TITLE
label("[INSERT TITLE]")
#CHECKS IF THIS IS THEIR FIRST TIME ON THE APP. IF IT IS, PRINT DESCRIPTION AND ASKS FOR USERNAME
searchfile = open("storefile.txt", "r")
with open ('storefile.txt', 'rt+') as in_file: #Open file lorem.txt for reading of text data.
for line in searchfile: #For each line of text store in a string variable named "line", and
if "1" not in line:#IT STORES '1' IN THE TEXTFILE WHEN THE USER FIRST OPENS THE CODE, SO IF '1' ISN'T THERE, THE USER HAS NOT OPENED THE CODE YET
print("yes")
Label(root,text="ENTER NAME",font=("System",15,"bold"),fg="steelblue").pack(side=LEFT)#enter name label
distance_text_box = Entry(root, bd=1)
distance_text_box.pack()
searchfile = open("storefile.txt", "a")
searchfile.write("1\n")
searchfile.close()
Button(root, text ="Done!", command=lambda:store()).pack(side=RIGHT)
elif "1" in line:
print("no")
Label(root,text="Welcome back,").pack()
searchfile.close()
#PUT NAME IN TEXTFILE
root.mainloop()
First of all, you are trying to open an already opened file.
Second, if you want to access a file line by line try this:
with open('file.txt','r') as f:
lines = f.readlines() #lines is now a list of lines in the file.
If you want to add new text to the file you can simply create a list of lines to add and append to it, once the check loop is done, append it to the lines list and write back to the file.
This function doesn't work and raises an error. Do I need to change any arguments or parameters?
import sys
def write():
print('Creating new text file')
name = input('Enter name of text file: ')+'.txt' # Name of text file coerced with +.txt
try:
file = open(name,'r+') # Trying to create a new file or open one
file.close()
except:
print('Something went wrong! Can\'t tell what?')
sys.exit(0) # quit Python
write()
If the file does not exists, open(name,'r+') will fail.
You can use open(name, 'w'), which creates the file if the file does not exist, but it will truncate the existing file.
Alternatively, you can use open(name, 'a'); this will create the file if the file does not exist, but will not truncate the existing file.
instead of using try-except blocks, you could use, if else
this will not execute if the file is non-existent,
open(name,'r+')
if os.path.exists('location\filename.txt'):
print "File exists"
else:
open("location\filename.txt", 'w')
'w' creates a file if its non-exis
following script will use to create any kind of file, with user input as extension
import sys
def create():
print("creating new file")
name=raw_input ("enter the name of file:")
extension=raw_input ("enter extension of file:")
try:
name=name+"."+extension
file=open(name,'a')
file.close()
except:
print("error occured")
sys.exit(0)
create()
This works just fine, but instead of
name = input('Enter name of text file: ')+'.txt'
you should use
name = raw_input('Enter name of text file: ')+'.txt'
along with
open(name,'a') or open(name,'w')
import sys
def write():
print('Creating new text file')
name = raw_input('Enter name of text file: ')+'.txt' # Name of text file coerced with +.txt
try:
file = open(name,'a') # Trying to create a new file or open one
file.close()
except:
print('Something went wrong! Can\'t tell what?')
sys.exit(0) # quit Python
write()
this will work promise :)
You can os.system function for simplicity :
import os
os.system("touch filename.extension")
This invokes system terminal to accomplish the task.
You can use open(name, 'a')
However, when you enter filename, use inverted commas on both sides, otherwise ".txt"cannot be added to filename