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())
Related
I am making some check-in system, just in case I want to build like a bot. But I am stuck building because my code returns syntax error. Can someone help me fix this?
I am making this code on Repl.it, one of the online IDE. I couldn't test it on eclipse because my python just isn't working.
import datetime
#This is where Name variable goes
#checkin = open(check-in.txt", "r")
i=0
while True:
it = input("Type in input: ")
if it == "Check-in list":
checkin = open("check-in.txt", "r")
if checkin.mode == "r":
contents = checkin.read()
print(contents)
checkin.close()
elif it == "Check-in":
checkin = open("check-in.txt", "a")
if checkin.mode == "a":
currentDT = datetime.datetime.now()
checkin.write((str(i+1) +". " + username + ":" + str(currentDT))
checkin.close()
Where error happens
checkin.close()
I have expect the output of "Type in input: " and when I type Check-in, the program should add number order, name, and time.
The output is: "SyntaxError: invalid syntax"
There are parentheses missing from checkin.write((str(i+1) +". " + username + ":" + str(currentDT)). Here is a fixed version: checkin.write((str(i+1) +". " + username + ":" + str(currentDT)))
Your parenthesis are not balanced. Add an extra ) after your checkin.write(... line.
Please bear with my as I am new to python and am learning by creating simple programs. Recently I started making my own program that generates a file and allows the user to choose things and store them in each file. In this example I was going for a song playlist generator. Although it was difficult I soldiered through until I came across this error that I couldn't fix. It was with the opening of a file.
This is the Code
cont = "0"
log = 0
data = open("songs.txt", "r")
songs = data.readlines()
songs.sort()
while log < 20:
cont = input("Do you want to make a playlist? [Yes or No]")
while cont == "yes":
print ("1. ", songs[0],"2. ", songs[1],"3. ", songs[2],"4. ", songs[3],"5. ", songs[4],"6. ", songs[5],"7. ", songs[6],"8. ", songs[7],"9. ", songs[8],"10. ", songs[9],"11. ", songs[10],"12. ", songs[11],"13. ", songs[12],"14. ", songs[13],"15. ", songs[14],"16. ", songs[15],"17. ", songs[16],"18. ", songs[17],"19. ", songs[18],"20. ", songs[19])
new = "playlist" + str(log) + ".txt"
print(new)
log = log + 1
cont = "no"
choice = int(input("Please enter the first choice of song you would like in your playlist [Type the allocated number please]"))
choice1 = choice - 1
"playlist" + str(log) + ".txt".append(songs[choice1])
However, my code is supposed to allow the user to choose songs from my print function and then add them to the playlist generatored and then repeat this for as many playlists they want. Now my code is giving me an error message.
File "playlists.py", line 18, in <module>
"playlist" + str(log) + ".txt".append(songs[choice1])
AttributeError: 'str' object has no attribute 'append'
What is this Error stating and also how can I overcome it.
Thanks in advance and anticipation!
The issue is that this line:
"playlist" + str(log) + ".txt".append(songs[choice1])
is just super wrong/sort of like pseudocode. To append to a text file requires you open it for appending and then write to it. Do this like so:
with open("playlist" + str(log) + ".txt", "a") as myfile:
myfile.write(str(songs[choice1]))
This section of code should write an input and another variable (Score) to a text file. The program asks for the input (so the if statement is definitely working) and runs without errors, but the text file is empty. Oddly, copying this code to an empty python file and running it works without errors. What is happening here?
if Score > int(HighScores[1]):
print("You beat the record with " + str(Score) + " points!")
Name = input("What is your name?")
BestOf = open("High Scores.txt", "w").close()
BestOf = open("High Scores.txt", "a")
BestOf.write(Name + "\n")
BestOf.write(str(Score))
I didn't close the file after appending.
BestOf.close()
fixed it
Try opening the file in 'w+' mode. This will create the file if it doesn't exist.
You can also check if the file exits using the 'os' module.
import os;
if Score > int(HighScores[1]):
print("You beat the record with " + str(Score) + " points!")
name = input("What is your name?")
if os.path.isfile("Scores.txt"):
fh = open("Scores.txt", "a")
else:
fh = open("Scores.txt", "w+")
fh.write(name + "\n")
fh.write(str(Score))
fh.close()
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")
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()