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))
Related
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 have a file config and the contents are separated by space " "
cat config
/home/user1 *.log,*.txt 30
/home/user2 *.trm,*.doc,*.jpeg 10
I want to read this file,parse each line and print each field from the each line.
Ex:-
Dir = /home/user1
Fileext = *.log,*.txt
days=30
I couldn't go further than the below..
def dir():
file = open('config','r+')
cont = file.readlines()
print "file contents are %s" % cont
for i in range(len(cont)):
j = cont[i].split(' ')
dir()
Any pointers how to move further?
Your code is fine, you are just missing the last step processing each element of the splitted string, try this:
def dir():
file = open('config','r+')
cont = file.readlines()
print "file contents are %s" % cont + '\n'
elements = []
for i in range(len(cont)):
rowElems = cont[i].split(' ')
elements.append({ 'dir' : rowElems[0], 'ext' : rowElems[1], 'days' : rowElems[2] })
for e in elements:
print "Dir = " + e['dir']
print "Fileext = " + e['ext']
print "days = " + e['days']
dir()
At the end of this code, you will have all the rows processed and stored in an array of dictionaries you can easily access later.
You can write a custom function to parse each line, and then use the map function to apply that function against each line in file.readlines():
def parseLine(line):
# function to split and parse each line,
# and return the formatted string
Dir, FileExt, Days = line.split(' ')[:3]
return 'Dir = {}\nFileext = {}\nDays = {}'.format(Dir, FileExt, Days)
def dir():
with open('config','r+') as file:
print 'file contents are\n' + '\n'.join(map(parseLine, file.readlines()))
Results:
>>> dir()
file contents are
Dir = /home/user1
Fileext = *.log,*.txt
Days = 30
Dir = /home/user2
Fileext = *.trm,*.doc,*.jpeg
Days = 10
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)
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()