So, in my python code I'm supposed to prompt the user for their name, address, and phone number and write that data as a line of comma separated values to the file using the directory and filename. Everything runs except the CSV part.
import os
import csv
def file_system():
"""Display information about users"""
direc = input("Enter name directory to save a file: ")
filename = input("Enter name of the file they want to save to the directory: ")
name = input("Enter your name : ")
address = input("Enter your address : ")
phone_number = input("Enter your phone number : ")
print (direc, filename, name, address, phone_number)
prompt = input()
if os.path.isdir(direc):
writeFile = open(os.path.join(direc,filename),'w')
writeFile.write (direc, + filename)
writeFile.close()
print("File contents:")
readFile = open(os.path.join(direc,filename),'r')
for line in readFile:
print(line)
readFile.close()
if prompt:
with open('Userdata.csv', 'a',
newline='') as outfile:
w = csv.writer(outfile)
w.writerow(name, address, phone_number)
print("File Updated")
else:
print("Directory doesn't exist, please enter again")
file_system()
The issue is with the evaluation of the if statement before the csv section.
run the code below twice, first time just pressing enter, second time typing something and then pressing enter...
prompt = input("input something:\n")
if prompt:
print("you got here")
else:
print("you didn't")
As you can see, when only pressing enter, the if statement becomes False...
Related
I used Python 3.6 version and now I want to save name & age at the file and then read the text as name + tab + age but I can't approach file read side.
My code:
while True:
print("-------------")
name=input("Name: ")
age=input ("Age: ")
contInput=input("Continue Input? (y/n) ")
fp.open("test.txt", "a")
fp.write(name+","+age+"\n")
if contInput=="n":
fp.close()
break
else:
continue
with open("test.txt", "r") as fp:
rd = fp.read().split('\n')
????
fp.close()
so I just confuse about file read. I want to print my saved data like below.
name [tab] age
but after used split method, rd type is list.
Can I divide name & age as each items?
fp.open("test.txt", "a")
At this point in your program, fp doesn't exist yet. Perhaps you meant fp = open(...) instead?
You're only closing the file if the user chose not to continue, but you're opening it every time through the loop. You should open and close it only once, or open and close it every time through the loop.
fp.write(name+","+"age"+"\n")
This writes the literal word age instead of the age variable. You probably wanted this instead: fp.write(name + "," + age + "\n")
Try this for your input loop:
with open("test.txt", "r") as fp:
for line in fp:
data = line.split(",")
name = data[0]
age = data[1]
problem
Doing a while loop to validate file extension. If a file extension is not .exe or .bat, ask user input again. I am looking for a solution without using import endswith break functions.
code
format = " "
while file[:-4] != ".bat" and file[:-4] != ".exe":
format = input("Enter file you like to open: ")
if format[:-4] == ".bat" or format[:-4] == ".exe":
callFunction(format)
else:
file = input("Enter file you like to open: ")
To follow Asking the user for input until they give a valid response and using os.path.splitext() to extract the file extension:
import os
ALLOWED_EXTENSTIONS = {".bat", ".exe"}
while True:
filename = input("Enter file you like to open: ")
extension = os.path.splitext(filename)[1]
if extension in ALLOWED_EXTENSTIONS:
break
with open(filename) as f:
# do smth with f
Without break:
import os
ALLOWED_EXTENSTIONS = {".bat", ".exe"}
extension = None
while extension not in ALLOWED_EXTENSTIONS:
filename = input("Enter file you like to open: ")
extension = os.path.splitext(filename)[1]
with open(filename) as f:
# do smth with f
Without break and without any imports:
ALLOWED_EXTENSTIONS = (".bat", ".exe")
filename = ""
while not filename.endswith(ALLOWED_EXTENSTIONS):
filename = input("Enter file you like to open: ")
with open(filename) as f:
# do smth with f
Without break and without any imports and without endswith():
ALLOWED_EXTENSTIONS = {"bat", "exe"}
filename = ""
while filename.rsplit(".",1)[-1] not in ALLOWED_EXTENSTIONS:
filename = input("Enter file you like to open: ")
with open(filename) as f:
# do smth with f
You don't need a loop
def ask_exe(prompt='Executable file name? '):
name = input(prompt)
if name[-4:] in {'.exe', '.bat'}: return name
return ask_exe(prompt='The name has to end in ".exe" or ".bat", please retry: ')
[no breaks, no imports, almost no code...]
As noted by ShadowRanger my code, that uses set notation for the membership test, is suboptimal for Python versions prior to 3.2. For these older versions using a tuple avoids computing the set at runtime, each and every time the function is executed.
...
# for python < 3.2
if name[-4:] in ('.exe', '.bat'): return name
...
I am using Python 2.7 and am trying to get my program to check if a file exists and if it does, the program should then ask the user if they want to overwrite it. If the file is not there, a new one should be created. These two steps are repeated where the file is found to be existing. Here is the code:
import os.path
file_name = input("Please enter the name of the file to save your data to: Example: test.txt ")
file_open = open(file_name, "w")
if os.path.isfile(file_name):
print ("File exists")
decide = input("Do you want to overwrite the file?, Yes or No")
control = True
while control:
if decide != "Yes":
file_name = input("Please enter the name of the file to save your data to: Example: test.txt ")
if os.path.isfile(file_name):
print ("File exists")
else:
newFile = open(file_name, "w")
newFile.write(str(model))
newFile.close()
control=False
else:
print("Creating a new file..................")
file_open.write(str(model))
file_open.close()
In lines 2, 6 and 10 it should be raw_input() as you are reading string, and check indentation of code.
I've created a function and got stuck on it.
Meaning of the function:
User types in a file, number and own name.
Program writes the name at the end of the file 'number' times.
And just prints out contents of the file.
What's the problem?
There are strange characters and a big space under it when program reads the file.
Like this: 圀漀爀氀搀眀椀搀攀㬀 ㈀ 㐀 ⴀ 瀀爀攀猀攀渀琀ഀഀ (and then there is a huge space for 10-15 lines in Powershell)
Error: 'str' object has no attribute 'close'.
def filemania():
print "Great! This way is called \"Filemania\""
file_name = raw_input("Type in any text file> ")
enter_1 = int(raw_input("Enter an integer> "))
enter_2 = raw_input("Enter your name> ")
print "Now your name will apear in the file %d times at the end" % enter_1
open_file = open(file_name, 'a+')
listok = []
while len(listok) < enter_1:
open_file.write(enter_2 + " ")
listok.append(enter_2)
print "Contains of the file:"
read_file = open_file.read()
print read_file
file_name.close()
filemania()
I think the problem is somewhere here:
open_file = open(file_name, 'a+')
Does somebody know how to solve these problems?
Firstly you set file_name = raw_input("Type in any text file> ") so you are trying to close a string with file_name.close():
When you write to open_file you move the pointer to the end of the file because you are appending so read_file = open_file.read() is not going to do what you think.
You will need to seek to the start of the file again to print the content, open_file.seek(0).
def filemania():
print "Great! This way is called \"Filemania\""
file_name = raw_input("Type in any text file> ")
enter_1 = int(raw_input("Enter an integer> "))
enter_2 = raw_input("Enter your name> ")
print "Now your name will apear in the file %d times at the end" % enter_1
# with automatically closes your files
with open(file_name, 'a+') as open_file:
listok = []
# use range
for _ in range(enter_1):
open_file.write(enter_2 + " ")
listok.append(enter_2)
print "Contains of the file:"
# move pointer to start of the file again
open_file.seek(0)
read_file = open_file.read()
print read_file
filemania()
For your second error, you are trying to close file_name, which is the raw input string. You mean to close open_file
Try that and report back.
def function(score,name):
sumOfStudent = (name + ' scored ' + str(score))
f = open('test.txt', 'wb')
f.write(sumOfStudent)
f.close()
user_name = input("Please enter yout full name: ")
user_score = int(input("Please enter your score: "))
function(user_score,user_name)
f = open('test.txt')
print(f.read())
f.close()
I was writing a simple program in python which allowed the user to enter information and then for that text to be stored in a .txt file. This worked however it would always write to the same line, I was wondering how I would make the f.write(sumOfStudent) on a new line every time (sumOfStudent is the variable to hold user input) Thanks!
Hey what you are doing is not writing to the end of the file you are overwriting everytime 'w' what you need to be doing is appending it to the file by using 'a'
f = open('test.txt', 'a')
Also to write to a new line you must tell the program thats what you're doing by declaring a new line "\n"
f.write(sumOfStudent + "\n")