reading from a text document in python using a variable - python

I my python GUI, I have created a questionaire. In this it allows me to ask questions and then save them to a text file. i have saved them to a text file using a variable, so each file is different. E.G.
name = james (the file will be called james)
or...
name = Charlie (the file will be called Charlie)
I am able to write and save to the text file. What I need to b able to do is find a way to open the text file by using a variable. this will allow me to input a name, such as "James" and I can open the file called James.
This is the code I have at the moment.
name = entry.get()
# this collects the name from an entry box.
newfile = (name.txt,"r")
# name is the variable I am using.
loaded = (newfile.read())
# this would hopefully put the file text into a variable
textbox.delete(0.0, END)
# this will clear the text box
textbox.insert(END, loaded)
# this put the text from the file (in loaded) into the text box
Is there a way to allow me to do this? I hope this makes sense. Thank you all who help.

First, you're not calling open anywhere. Just writing, e.g., (path, "r") doesn't give you a file object, it just gives you a tuple of two strings.
Second, literal strings have to be in quotes. And if you want to concatenate two strings, it doesn't matter whether they're in variables or literals, that's just +.
So:
newpath = name + ".txt"
newfile = open(newpath, "r")
Also, while you're at it, you should close the file somewhere. Ideally by using a with statement:
newpath = name + ".txt"
with open(newpath, "r") as newfile:
loaded = newfile.read()

Related

Create text file in folder

I'm trying to create a text file that is named using a variable in my program. Only problem is, I can't specify a directory when i'm naming it using a variable. (vac_postcode is the variable i'm using to name the file)
centrebypostcode = open(C:\Users\Rich\Desktop\Assignment\Centre\vac_postcode + ".txt"', "a+")
centrebypostcode.write("\n")
centrebypostcode.write(vac_center)
centrebypostcode.close()
I'm using "a+" because I need the program to create the text file if it doesn't exist, but if it does, it just appends what I need it to, to the text file. (This is my understanding of the usage of "a+")
open(r'C:\Users\Rich\Desktop\Assignment\Centre\vac_postcode + ".txt"', "a+" ') does not work either, unfortunately.
You have to keep the variable name outside the quoted string, change the line to
centrebypostcode = open(r"C:\Users\Rich\Desktop\Assignment\Centre" + "\\" + vac_postcode + ".txt", "a+")
Edited: the raw string literal cannot have the last backslash, so you need to concatenate that separately.
It looks like that quotation is wrong.
try with this
centrebypostcode = open(r"C:\Users\Rich\Desktop\Assignment\Centre\{}.txt".format(vac_postcode), "a+")
I just try to be more descriptive
filenames = ["my_file1","my_file2"]
for filename in filenames:
filename = f"C:\Users\Rich\Desktop\Assignment\Centre\vac_postcode\{filename}.txt"
with open(filename, "a+") as fh:
fh.write("Hello world")

How to replace contents in file in python

I have a script in python, part of the script involves me creating a .txt file with contents i will need to use throughout the script
my_file = open('number.txt', 'w')
my_file.write(str(30))
my_file.close()
There are two things i'm stuck on, firstly, considering there will only ever be one number in the file, how would i open it and assign the contents to a variable. I know to open the file and read it would be something like this:
my_file = open('number.txt', 'r')
but then i want to assign the contents which right now is 30 to a variable called 'num' which i could use throughout the rest of my script.
Secondly, how could i replace the contents of the file. as in re-open it and replace the 30 with a different number, and would this also change automatically for the variable aswell?

How to save contents of a list to a file?

I have some question about my code:
def entry_book():
book = ["autor", "ime", "godina", "ISNB", "zanr", "cena", "broj"]
print ("Podaci za knjigu:")
book[0] = input ("Autor: ")
book[1] = input ("Naslov: ")
book[2] = input ("Godina: ")
book[3] = input ("ISNB: ")
book[4] = input ("Zanr: ")
book[5] = input ("Cena: ")
book[6] = input ("Kolicina: ")
record= "{}|{}|{}|{}|{}|{}|{}".format (book[0], book[1], book[2], book[3],
book[4], book[5], book[6])
print (book)
print (record)
f = open('books.txt','w')
f.write (record)
f.close()
f = open("books.txt")
x = f.read()
f.close()
print (x)
record1 = record.split('|')
print (record1)
second_meni()
This is code to store information on books, which I want to access later (like at a library). However, every time I add/create a new book, the old one gets deleted. Can anyone help me rewrite the code so it can store the old data as well. Or please explain what is the correct way to do it?
You have to use
f = open('knjige.txt', 'a')
'w' recreates the file (so use it only for NEW files, or if you don't mind it will be overwritten, 'a' appends to a file.
See python open built-in function: difference between modes a, a+, w, w+, and r+?
Also some unrelated suggestions:
Use the add instead of indices, or even better: use a dictionary
Use English variable names/comments.
Use code to check if the file read/write is ok, what if the file cannot be
written because of access restrictions or too less space on the disk?
Use different functions for the input, writing and printing, it makes testing/maintainability/extension much easier.
I took the liberty of pythonizing your code a bit.
def unos_knjiga():
headers = ["Autor", "Naslov", "Godina", "ISNB", "Zanr", "Cena", "Kolicina"]
print("Podaci za knjigu:")
knjiga = [input("{}".format(obj + ': ')) for obj in headers] # see 1
zapis = '|'.join(knjiga) # see 2
print(knjiga)
print(zapis)
with open('knjige.txt', 'a') as f: # see 3
f.write(zapis + '\n')
# i guess this is for testing?
with open("knjige.txt", 'r') as f:
x = f.read()
print(x)
# and this too?
zapis1 = zapis.split('|')
print(zapis1)
# this is not mentioned anywhere
second_meni()
1) This is a list comprehension. It creates lists by looping through stuff. In this case we are looping through the header list and use its items to construct input statements. The provided input is stored in the list.
2) .join() method. It does what you explicitly did. Joins items from iterators using a string between them.
3) the with keyword. Manages files so that you do not have to. Unless there is a reason not to use it, use it. This was also where the real problem with your code was. You have to use the 'a' mode. 'a' is for append, 'w' is for write. In this context, write means delete everything that was there and write this new stuff. Also note that 'a' mode can also create files, you do not need to temporarily switch to 'w' for that ('r' does not; 'r' is for read).
Cheers!
I think there are two methods to do this:
FIRST
f = open('knjige.txt','w')
is the piece of code which is responsible for rewriting the existing data in your file.
Other option which python offers to append some new data to the existing data is to open a file for writing using append 'a' method. So you can replace your above statement with
f = open('knjige.txt','a')
It won't replace the file with new data you enter.
SECOND
Other option is to open your file in read method, f = open('knjige.txt','r') and copy the existing data to a variable ( variable=f.read('knjige.txt') ). You can also use pickle module and its functions dump and load if you need to maintain your datatype.
Now concatenate your new data to the values in 'variable' and again open the file in write method and write it back to it.
Your call to open the file, f = open('knjige.txt','w') opens the file, truncating the existing contents should it exist. If you open the file with a mode that appends contents, like a it should not delete previous lines. See https://docs.python.org/2/library/functions.html#open for more information on opening files for reading / writing.

Why wasn't my file opened?

I'm working on a project at the end of a book I read for Python, so in case this hasn't given it away for you, I'm still quite new to this.
I'm trying to use the open command to open a file that I know exists. I know that the code understands the file is there, because when I switch over to write mode, it clears my text file out, telling me that it can find the file but it just won't read it. Why is this happening? Here's the code-
openFile = open('C:\\Coding\\Projects\\Python\\One Day Project\\BODMAS\\userScores.txt', 'r')
def getUserPoint(userName):
for line in openFile:
split(',')
print(line, end = "")
I've tried a few variations where my openFile function is a local variable inside getUserPoint(), but that didn't make a difference either.
Editing because I missed a vital detail — the userScores.txt file is laid out as follows:
Annie, 125
The split() function is supposed to split the name and the score assigned to the name.
Your function isn't valid Python, as split isn't a globally defined function, but a built-in function of the type str. Try changing your function to something like this.
def getUserPoint(name):
for line in openFile:
line_split = line.split(",")
print(line_split, end = "")

Python hash from file not as expected

My problem is the following:
I want to create a little tool in Python that creates hash values for entered text or from files. I've created all necessary things, GUI, option to select between hash functions, everything is fine.
But when I was testing the program, I realized, that the from files generated hashes aren't the same as the ones given by most download pages. I was confused, downloaded some other hashing tools, they all gave me the same hash as provided on several websites, but my tool always give some other output.
The odd thing is, the hashes generated from "plain text" are in my and in all other tools identical.
The app uses wxPython, but I've extracted my hash function for hash creation from files:
import os, hashlib
path = "C:\file.txt" # Given from some open file dialog, valid file
text = ""
if os.path.isfile(path):
text_file = open(path, "r")
text = text_file.read()
text_file.close()
print hashlib.new("md5", text).hexdigest() # Could be any hash function
Quite simple, but doesn't work as expected.
It seems to work if there's no new line in the file (\n)?
But how to make it work with newline? It's like every file has more than one line.
It is a problem of quoting the backslash character, see https://docs.python.org/2/reference/lexical_analysis.html#literals. Use two backslashes to specify the file name. I would also recommend reading the file in binary mode. As a precaution, print the length of variable text to make sure the file was read.
import os, hashlib
path = "C:\\file.txt" # Given from some open file dialog, valid file
text = ""
if os.path.isfile(path):
text_file = open(path, "rb")
text = text_file.read()
text_file.close()
print len(text)
print hashlib.new("md5", text).hexdigest() # Could be any hash function
Try splitting text update and md5 object creation as below
import hashlib;
md5=hashlib.new('md5')
with open(filepath,'rb') as f:
for line in f:
md5.update(line)
return md5.hexdigest()

Categories

Resources