count = 0
answer = ""
pass_pool={"CSRP":"","pos":"","erp":"","comverse":"","miki":"","citrix":""}
name = ""
def program_start():
answer = input('Do you want to make some TXT with the same passwords? y\\n :')
count = int(input('How many TXT files do you want to make?'))
name = input('Enter the hot user id:')
name = name+".TXT"
password_collector() # collect password to pass_pool dictionary
create_file() #create TXT file. it has to be in capital "TXT"
#for the safe program.
def create_file():
newTXT = open(name, "w")
newTXT.write(name + "\n \n" )
for system , password in pass_pool.items():
newTXT.write(system + ":" + password )
newTXT.close()
I get:
File "C:\Python33\mypy\txt creator.py", line 16, in create_file
newTXT = open(name, "w")
FileNotFoundError: [Errno 2] No such file or directory:
From what I look on google this error mean wrong path or file not found. But I check with sys.path and saw that "C:\Python33\mypy" in my paths, and I create the file with "w" so it should work with no problems.
When I used only the create_file() function in the shell it works with no problem.
When you set the value of name in program_start, Python creates a variable name local to that function's scope, which masks the global name, so the global value remains unchanged. In create_file you use the unchanged global name, which equals to "", and opening a file with the name "" gives you an error.
The quick-and-dirty fix would be adding
global name
in the beginning of program_start. But it is much clearer to write
count = 0
answer = ""
pass_pool={"CSRP":"","pos":"","erp":"","comverse":"","miki":"","citrix":""}
def program_start():
answer = input('Do you want to make some TXT with the same passwords? y\\n :')
count = int(input('How many TXT files do you want to make?'))
name = input('Enter the hot user id:')
name = name+".TXT"
password_colector() # collect password to pass_pool dic
create_file(name) #create TXT file. it has to be in capital "TXT"
#for the safe pogram.
def create_file(name):
newTXT = open(name, "w")
newTXT.write(name + "\n \n" )
for system , password in pass_pool.items():
newTXT.write(system + ":" + password )
newTXT.close()
Related
I have tried multiple ways to do this but I struggle. I am new to Python trying to learn currently.
CustomerList = []
Customers = {}
Dates = {}
while True:
Customer_Name = input("Customer's Name:")
CustomerList.append(Customer_Name)
Customers_Address = input("Customer's Address:")
if Customer_Name in Customers:
Customers[Customer_Name]['Orders'] += 1
Customers[Customer_Name]['TotalAmount'] = Total_Amount
else:
Customers[Customer_Name] = {}
Customers[Customer_Name]['Address'] = Customers_Address
Customers[Customer_Name]['Orders'] = 1
Customers[Customer_Name]['TotalAmount'] = 0
file1 = open('Orders_Per_Users.txt', 'w')
file1.write(Customer_Name + " has ordered " + str(Customers[Customer_Name]['Orders']) + " times in total\n")
file1.close()
This is the output
And this is what I get exported from this output
What I want to .txt export for example is.
John has ordered 1 times in total
Mike has ordered 1 times in total
etc
etc
Opening with a 'w' tag means you are opening the file in write mode. write mode overwrites the previously existing text if any or creates a new file if the file doesnt exist.So what you might wanna do is opening it in 'a' mode (append mode) so that it doesnt overwrite the file but just appends text to it
file1 = open('Orders_Per_Users.txt', 'a')
file1.write(Customer_Name + " has ordered " + str(Customers[Customer_Name]['Orders']) + "
times in total\n")
your file permission should be append
w -
Opens in write-only mode. The pointer is placed at the beginning of
the file and this will overwrite any existing file with the same name.
It will create a new file if one with the same name doesn't exist
a -
Opens a file for appending new information to it. The pointer is
placed at the end of the file. A new file is created if one with the
same name doesn't exist. .
file1 = open('Orders_Per_Users.txt', 'a')
I hope you're enjoying your learning :)
problems are:
your code just update the text each time you add an item because of the mode of write/read operation of the file, you coded it like this:
file1 = open('Orders_Per_Users.txt', 'w')
While the correct mode is 'a' instead of 'w' to append to the file without erasing old written text!
NOTE: even if you correct it to be 'a' another issue will appear! the line will be written again in entering new order!
So what you should do is closing the file file1.close() each time you write to it in the while so your code will be looks like this:
CustomerList = []
Customers = {}
Dates = {}
while True:
Customer_Name = input("Customer's Name:")
CustomerList.append(Customer_Name)
Customers_Address = input("Customer's Address:")
if Customer_Name in Customers:
Customers[Customer_Name]['Orders'] += 1
Customers[Customer_Name]['TotalAmount'] = Total_Amount
else:
Customers[Customer_Name] = {}
Customers[Customer_Name]['Address'] = Customers_Address
Customers[Customer_Name]['Orders'] = 1
Customers[Customer_Name]['TotalAmount'] = 0
file1 = open('Orders_Per_Users.txt', 'a')
file1.write(Customer_Name + " has ordered " + str(Customers[Customer_Name]['Orders']) + " times in total\n")
file1.close()
Ok so I have a the name of a file as an raw input. But I the code to only use an already existing file and not and not be able to type in everything and just create new files.
So how can I make the program only use an already existing file and NOT create a new one if the input is wrong?
lista = {"police":"911"}
functiontext = raw_input("call function ")
arguments = raw_input("input file name ")
def save(lista,arguments):
filen = arguments
spara = lista
fil = open(filen + ".txt","w")
for keys, values in spara.items():
spara_content = keys + ": " + values + "\n"
fil.write(spara_content)
fil.close()
Consider using os.path.exists() or os.path.isfile() to test if the file is there. For example:
def save(lista,arguments):
filen = arguments
spara = lista
fname = filen + ".txt"
if os.path.isfile(fname):
fil = open(filen + ".txt","w")
else:
print("The file {} does not exist, skipping".format(fname))
File = input("Please enter the name for your txt. file: ")
fileName = (File + ".txt")
WRITE = "w"
APPEND = "a"
file = []
name = " "
while name != "DONE" :
name = input("Please enter the guest name (Enter DONE if there is no more names) : ").upper()
fileName.append(name)
fileName.remove("DONE")
print("The guests list in alphabetical order, and it will save in " + fileName + " :")
file.sort()
for U in file :
print(U)
file = open(fileName, mode = WRITE)
file.write(name)
file.close()
print("file written successfully.")
I am just practicing to write the file in Python, but something bad happened.
Here are still some errors about this:
fileName.remove("DONE")
Still showing 'str' error.
filename=filename+name
Use the above code
Python strings are immutable. Therefore you can't use append() on them. Use += instead:
fileName += name
which is shorthand for
fileName = fileName + name
Note how nothing is appended to the string, instead a new one is created and then assigned to fileName.
Try this.
I thought you have some mistaken in variable name.
aFile = input("Please enter the name for your txt. file: ")
fileName = (aFile + ".txt")
WRITE = "w"
APPEND = "a"
file = []
name = " "
while name != "DONE" :
name = input("Please enter the guest name (Enter DONE if there is no more names) : ").upper()
file.append(name)
file.remove("DONE")
print("The guests list in alphabetical order, and it will save in " + fileName + " :")
file.sort()
for U in file :
print(U)
outputfile = open(fileName, mode = WRITE)
outputfile.write(name)
outputfile.close()
print("file written successfully.")
Just right out the bat, you can not append to a toople.
fileName.append(name) #how can you append or remove anything into or from this when it contains toople?
Another thing, I don't know what version of python you are using but, I never seen expression like this
file = open(fileName, mode = WRITE) #this should be something like (file=open(fileName,"w"))
Just overall check your code. Like I said you can not add or remove stuff from a toople; only in lists and dictionaries.
append is the list's method where as fileName declared in your code is treated as string. If your intention is to append the string to file, open the file in "append" mode and write to it:
with open(aFile + ".txt", "a") as f:
f.write("appended text")
This is my code to opening the file; I would like it to contain a name and a figure:
file_n = "Class_" + str(num_class) + ".txt"
file = open(file_n,"r")
string = file.read()
file.close()
and this is the error message I keep getting and I can't work out how to fix it:
file = open(file_n,"r")
IOError: [Errno 2] No such file or directory: 'Class_2.txt'
Could someone please tell me why this happening and the solution to it?
im still very confused
this is my whole code:
import random
import json
score = 0
turn = 1
turn = turn + 1
name = raw_input("what is your name?")
num_class = input("What class are you in? (1,2,3)")
print ("hello "+name+" have fun and good luck!")
for turn in range(10):
randnum_1 = random.randint(1,10)
randnum_2 = random.randint(1,10)
operators = ["+", "-", "*"]
operator_picked = operators[random.randint(0,2)]
human_answer = raw_input("What is " + str(randnum_1) +" "+ operator_picked +" " + str(randnum_2) + "?")
correct_answer = str((eval(str(randnum_1) + operator_picked + str(randnum_2))))
if correct_answer == human_answer :
score = score+1
print ("Correct!")
else:
print ("Incorrect!" +"The correct answer is " + str(correct_answer))
print("\nYour score was " + str(score)+ "/10")
file_name = ("Class_" + str(num_class) + ".txt")
file = open(file_n,"r")
string = file.read()
file.close()
dict = {}
Like Kevin and Flavian mentioned the directory of Class_2.txt is most likely not the directory where your script is located.
file_n = "/ActualDirectory/ofFile/Class_" + str(num_class) + ".txt"
Make sure that your Python code lies in the same directory with your txt file.
So it should be like this:
Of course the two files can be in different directories, but then you should provide the relevant, or absolute, path of the txt file to your code.
As 1001010 stated, you could check your current directory by doing:
import os
print(os.getcwd())
I'm currently working on a task where I must store scores in a text file. This is my code thus far:
def FileHandle():
score = str(Name) + ": " + str(correct)
File = open('Test.txt', 'a')
File.write(score)
File.close()
Name = input("Name: ")
correct = input("Number: ")
FileHandle()
My question is, how would I check already existed names in the text file and only add their score, rather than name and score, to the line it existed on?
This is what the file looks like:
Jonathon: 1
Micky: 5
How it would look after adding a score:
Jonathon: 1, 4
Mickey: 5
# The score added here is Jonathon's 4
Attempt:
# Accept scores
name = input("Name: ")
correct = input("Number: ")
if name in grade_book.keys and "," in grade_book.keys <= 2():
grade_book[name] += ',' + correct
else:
grade_book[name] = correct
If you are entering many scores at a time, I suggest reading the file into memory and working with things there. Doing an open/close on the file for every score update is very inefficient.
# Read the file into a dictionary
grade_book = {}
File = open('Test.txt', 'r')
for line in File:
name, scores = line.split(':')
grade_book[name] = scores.strip()
File.close()
print grade_book
# Accept scores
name = raw_input("Name: ")
while name != "":
correct = raw_input("Number: ")
if name in grade_book.keys():
grade_book[name] += ',' + correct
else:
grade_book[name] = correct
name = raw_input("Name: ")
# Write dictionary back to the file
File = open('Test.txt', 'w')
for name, scores in grade_book.items():
out_line = name + ':' + scores + "\n"
File.write(out_line)
File.close()
Unfortunately you would have to go over the file, find the correct line, edit it and write in a temp file and then move that file to original. Best first use a data structure like dict etc. to update scores and finally when done write or persist them.
def filehandle(name,correct):
temp = open('temp', 'wb')
with open('Test.txt', 'r') as f:
for line in f:
if line.startswith(name):
line = line.strip() + correct +'\n'
temp.write(line)
temp.close()
shutils.move('temp', 'data.txt')
You need to pass in the parameters while calling the functions.
Name = input("Name: ")
correct = input("Number: ")
filehandle(name, correct)