I've been playing around with Python a bit recently and have come across this error when creating functions. I can't seem to fix it :(. CODE:
Python
#Python
choice = input('Append Or Write?')
if choice == "write":
def write():
pass
text_file = open('WrittenTXT.txt', "w")
type_user = input('Type: ')
text_file.write(type_user)
text_file.close()
if choice == "append":
def append():
# Making a txt file
#Append
pass
text_file = open('WrittenTXT.txt', "a")
user_int = input('Enter An Integer: ')
space = "\n" * 2
lines = [space, "Hi\n", "Hallo\n", "Bonjour\n", user_int]
text_file.writelines(lines)
text_file.close()
You forgot to call your functions that you defined. pass may also be causing the statements in your function to get ignored, remove pass.
Reformatting your code:
#Python
def append():
# Making a txt file
#Append
# pass
text_file = open('WrittenTXT.txt', "a")
user_int = input('Enter An Integer: ')
space = "\n" * 2
lines = [space, "Hi\n", "Hallo\n", "Bonjour\n", user_int]
text_file.writelines(lines)
text_file.close()
def write():
# pass
text_file = open('WrittenTXT.txt', "w")
type_user = input('Type: ')
text_file.write(type_user)
text_file.close()
choice = input('Append Or Write?')
if choice == "write":
write()
if choice == "append":
append()
Related
Im supposed to make a function for adding name and number to a.txt file, and one for reading the file. What am I doing wrong and how do I correct it? first post so I dont know if something is in the wrong format, sorry.
def add():
while True:
name = input("Name and number: ")
with open("Telefon.txt", "a") as f:
f.write(name)
f.close()
if name == "Enter":
break
def read():
f = open("Telefon.txt", "r")
print(f.read)
There are certain logical and optimizations mistake in your code you should not open file again and again and close it in loop, also use empty condition to terminate the loop e.g. press enter without entering any thing. For reading, I replaced your read method with redlines method
def add():
with open("Telefon.txt", "a") as f:
while True:
name = input("Name and number: ")
f.write(name + '\n')
if name == "":
break
def read():
f = open("Telefon.txt", "r")
print("".join(f.readlines()))
add()
read()
The output is following
I am trying to write a login function using python. However, I can't seem to write the code for checking the username and password against the ones stored in a file. The specific error is NameError: name 'adusername' is not defined. How do I fix this?
def adminlogindetails():
adusername = input("Admin Username: ")
adpassword = input("Admin Password: ")
adfile = open("adlogindetails.txt", "a")
adfile.write(adusername)
adfile.write(",")
adfile.write(adpassword)
adfile.write("\n")
adfile.close()
def adminverification():
adun = input("Enter your username:")
adpw = input("Enter your password:")
adinfo = open("adlogindetails.txt", "r")
for line in adinfo:
adun, adpw = line.split(",")
if adun == adusername and adpw == adpassword:
print("Login successful!")
adminoptions()
else:
print("Incorrect username/password")
roleselection()
adminverification()
You have not declared adusername and adpassword in adminverification(). So, it is causing the error. If you want to use the variables from adminlogindetails(), change the variables name since you have stored the details in adlogindetails.txt.
The below code should be changed as line variable contains the already stored username and password:
adun, adpw = line.split(",")
Change above piece of code to the shown below:
adusername, adpassword = line.split(",")
you can use this:
def adminlogindetails():
adusername = input("Admin Username: ")
adpassword = input("Admin Password: ")
adfile = open("adlogindetails.txt", "a")
adfile.writelines(adusername + ',' + adpassword )
adfile.close()
def adminverification():
adun = input("Enter your username:").strip()
adpw = input("Enter your password:").strip()
with open("adlogindetails.txt", "r") as f:
lines = f.readlines()
i = 0
for line in lines:
adusername, adpassword= line.split(",")
adusername = str(adusername).strip()
adpassword = str(adpassword).strip()
if (adun == adusername) and (adpw == adpassword):
print("Login successful!()")
adminoptions()
break
else:
i += 1
if i >= len(lines): #If no any match upto last line, this will be true
print("Incorrect username/password")
roleselection()
break
adminverification()
First of all you are not calling adminlogindetails().
Also adusername is a local variable and you should either make it global using global adusername in the adminlogindetails function or declare it outside of the functions in the global scope.
See this - https://www.w3schools.com/python/python_scope.asp
This line is your problem:
adun, adpw = line.split(",")
"adun" and "adpw" are your inputs and you are overwriting them. Replace with this and it will be ok:
adusername, adpassword = line.replace("\n", "").split(",")
Note: "\n" needs to be removed for your comparison to be ok.
If I have this code to write a txt file I am just wondering why every time I type \n in the input it doesn't create a newline so like this.
This is the example txt file\n it doesn't create a new line\n how can I make it do it?
This is the code
def create():
path = input("What file would you like to create: ")
output_file = open(path, 'x')
text = input("What would you like to write? ")
output_file.write(text)
output_file.close()
def append():
path = input("What file would you like to append: ")
output_file = open(path, 'a')
text = input("What would you like to write?")
output_file.writelines(["\n", text])
output_file.close()
write = input("Would you like to write something today, or edit? ")
if write == "Write":
create()
if write == "Edit":
append()
You can use replace:
def create():
path = input("What file would you like to create: ")
output_file = open(path, 'x')
text = input("What would you like to write? ")
output_file.write(text.replace('\\n', '\n'))
output_file.close()
def append():
path = input("What file would you like to append: ")
output_file = open(path, 'a')
text = input("What would you like to write?")
output_file.writelines(text.replace('\\n', '\n'))
output_file.close()
write = input("Would you like to write something today, or edit? ")
if write == "Write":
create()
if write == "Edit":
append()
Here's a very simplified answer.
input = input("Would you like to Write a new document, or Edit an existing one? ")
if input == Write:
file = open(path, "w")
file.write(text)
file.write("\r\n")
file.close()
if input == Edit:
file = open(path, "a")
file.write(text)
file.write("\r\n")
file.close()
The reason why \n doesn't work with input is mentioned in How do you input escape sequences in Python?. The input function doesn't recognize any escape sequences, such as \n, because it interprets the text literally.
To interpret \n as a new line from text, have these imports and adjust the arguments for write() and writelines() allowing a user to input, This is the example txt file\n it doesn't create a new line\n how can I make it do it? to include new lines:
import ast # Add imports
import shlex
def create():
path = input("What file would you like to create: ")
output_file = open(path, 'x')
text = input("What would you like to write? ")
output_file.write(ast.literal_eval(shlex.quote(text))) # Evaluate escape sequences
output_file.close()
def append():
path = input("What file would you like to append: ")
output_file = open(path, 'a')
text = input("What would you like to write?")
output_file.writelines(["\n", ast.literal_eval(shlex.quote(text))]) # Evaluate escape sequences
output_file.close()
write = input("Would you like to write something today, or edit? ")
if write == "Write":
create()
if write == "Edit":
append()
I am trying to call the list I created in a sub-function, into another sub-function. Using parameters and call functions are my Achilles heel as it relates to python. I want to call the newList I created in the calculateZscore function, into mu globalChi function.
My current code:
import os
import math
'''
c:/Scripts/Lab2Data
NCSIDS_ObsExp.txt
chisquare.txt
output.txt
'''
def main():
directory = raw_input ("What is the working directory? ")
input_file = raw_input ("What is the name of the input file? ")
chiTable = raw_input ("What is the name of the chi-squared table? ")
outPut = raw_input ("What is the name of the output file? ")
path = os.path.join(directory,input_file)
path_1 = os.path.join(directory, chiTable)
path_2 = os.path.join(directory, outPut)
if __name__ == "__main__":
main()
def calculateZscore(inFileName, outFileName):
inputFile = open(inFileName,"r")
txtfile = open(outFileName, 'w')
for line in inputFile:
newList = line.strip().split(',')
obsExp = newList[-2:]
obsExp = list(map(int, obsExp))
obs = obsExp[0]
exp = obsExp[1]
zScore = (obs - exp) / math.sqrt(exp)
zScore = map(str, [zScore])
newList.extend(zScore)
txtfile = open(outFileName, 'w')
txtfile.writelines(newList)
inputFile.close() #close the files
txtfile.close()
return newList #return the list containing z scores
def globalChi(zscoreList):
print newList
You should read about the return statement. It is used to make a function return a result (the opposite of taking an argument), and cannot be used outside a function.
Here, you are doing the exact opposite.
I am making a program that lets you edit, or read a text document in python, and I'm not finished yet, and I'm stuck on the reading part. I want it to print only one line, and I'm drawing a blank on how to do so. The read part is in "def read():"
def menu():
print("What would you like to do?")
print("\n(1) Write new text")
print("(2) Read line 3")
choice = float(input())
if choice == 1:
write()
elif choice == 2:
read()
def read():
with open('test.txt', 'r') as read:
print()
def write():
print("\nType the full name of the file you wish to write in.")
file1 = input().strip()
with open(file1, "a") as add:
print("What do you want to write?")
text = input()
add.write("\n"+ text)
menu()
def read():
with open('test.txt', 'r') as f:
for line in f:
print(line)
Edit:
def read():
with open('test.txt', 'r') as f:
lines = f.readlines()
print lines[1]
You can use the file as an iterable, and loop over it, or you can call .next() on it to advance one line at a time.
If you need to read 1 specific line, this means you can skip the lines before it using .next() calls:
def read():
with open('test.txt', 'r') as f:
for _ in range(2):
f.next() # skip lines
print(f.next()) # print the 3rd line
I figured mine out pretty late since i do not use the 'def' function, but this prints out the line that you want to print
import os.path
bars = open('bars.txt', 'r')
first_line = bars.readlines()
length = len(first_line)
bars.close()
print(first_line[2])