Consider the following code:
import pickle
def open_file(fname, fname1 = None):
# returns a new OPEN file
if fname1:
while fname == fname1:
f_name = input("File already open, filename: ")
f = None
while not f:
try:
f = open(fname, "rb")
except IOError:
fname = input("File not found, filename: ")
print(fname, "open")
return f
def get_2cubes():
a_name = input("\nWhat is the name of the first cube's file? ")
a_file = open_file(a_name)
#a_cube = pickle.load(a_file)
a_file.close()
b_name = input("\nWhat is the name of the second cube's file? ")
b_file = open_file(b_name, a_name)
#b_cube = pickle.load(b_file)
b_file.close()
#return a_cube, b_cube
get_2cubes()
The code is meant to open a second file only if it's not the first file.
The first file's name is represented by fname1 in open_file(). If the name of the second file (b_name in this case) matches that of the first file the user will be prompted to enter a new name.
I supplied a default argument of None for the fname1 parameter because the function will sometimes be used only for opening one file and not for also comparing it to another file. However, I can't seem to override the default argument.
The a_name variable from the 7th line of get_2cubes is not being recognized by the if fname1: condition in open_file, and as a result I can open the same file twice. How would I correct this?
I think you need to use raw_input. Otherwise the text entered will treated as a variable name, and therefore will equal to None. (Unless you're on Python 3)
Related
I'm trying to verify if a file exists or not in the current directory. At the same time, read if the file exists. The below is my code
import os.path
def readdata():
isFileExist = False
while isFileExist == False:
userIN = str(input("Please Enter a file name, followed by .txt: "))
isExist = os.path.exists(userIN)
if isFileExistExist == False:
print(f"Checking... {userIN} DOES NOT exist in the current directory. Please retry.")
else:
print(f"Checking... {userIN} exist in the current directory.")
print(f"\n The file < {userIN} > includes the following data:")
IN = open(userIN,"r")
std1N = IN.readline()
std1M = IN.readline()
std2N = IN.readline()
std2M = IN.readline()
std3N = IN.readline()
std3M = IN.readline()
IN.close()
print(f" Student Name: {std1N.strip()}")
print(f" Performance: {std1M.strip()} out of 100")
print(f" Student Name: {std2N.strip()}")
print(f" Performance: {std2M.strip()} out of 100")
print(f" Student Name: {std3N.strip()}")
print(f" Performance: {std3M.strip()} out of 100")
print(f" The average exam score of the 3.0 students in the file < {userIN} > is {(eval(s1M.strip())+eval(s2M.strip())+eval(s3M.strip()))/3:.2f}.")
def main():
readdata()
if __name__ == '__main__':
main()
How to use main to transfer file name to the function readdata()? And then verify if it exists in the current file directory and read the file. As well as, getting the average 3 student's average in that file. I want to transfer the filename from main to readdata() function. How can I achieve that? Thank you for your time and consideration
There is a couple of methods to check it.
try except
try:
file = open(file_name)
except FileNotFoundError:
# do something when file not exist
pathlib.Path object has exists method.
os.path.isfile method
To read data from file use:
with open(file_name) as f:
for line in f:
# do something with current line
# context manager close file automaticly
or
with open(file_name) as f:
lines = f.readlines()
for line in lines:
# do something with current line
Second way is worse then first because:
first one uses generator
second one uses creates and use list (slower and use more memory)
But in your case you need to read 2 lines per iteration so you can use readline method 2 times per iteration and break it when readline return None.
e.g
with open(file_name) as f:
current_name = f.readline()
current_performance = f.readline()
while current_name is not None:
# do something
current_name = f.readline()
current_performance = f.readline()
You can also extend condition with a and current_performance is not None to be sure that u have both values.
Good day everyone, How can i make this thing make TRUE? I already have existed .txt files but the outcome always False.
ID = input("Enter the name of your .txt file: ") +".txt" +"'"
IDS = "'" + ID
file_exists = os.path.exists(IDS)
print(file_exists)
print(IDS)
Get rid of ' before and after the file name:
ID = input("Enter the name of your .txt file: ") +".txt"
file_exists = os.path.exists(ID)
print(file_exists)
print(ID)
For example, if you had foo.txt and you put foo into your program, then your current code would look for a file named 'foo.txt', not foo.txt.
Try this:
#You may want to use str.strip() to get rid of unnecessary whitespaces
ID = input("Enter the name of your .txt file: ").strip() + ".txt"
file_exists = os.path.exists(ID)
print(f'{ID} exists') if file_exists else print(f'{ID} file does not exist')
Remove the quotes, you are adding single quotes to start and end of your string. Your code should look like this:
ID = input("Enter the name of your .txt file: ") +".txt"
file_exists = os.path.exists(ID)
print(file_exists)
print(IDS)
Quotes in programming languages indicate what are strings, and they are omitted by the interpreter when you output it into a terminal (print)
I'm reading from a .txt file that has one line of text (YPerson18) I'm wondering if there is a smarter way of writing this code preferably using a for loop.
import os
parent_dir = "../dirfiles"
os.chdir(parent_dir)
file_name = "userdata.txt"
append_mode = "a"
read_mode = "r"
read_file = open(file_name, read_mode)
the_lines = read_file.read(1)
print("Initial of the first name is: {}".format(the_lines))
the_lines = read_file.read(6)
print("The last name is: {}".format(the_lines))
the_lines = read_file.read(8)
print("The age is: {}".format(the_lines))
read_file.close()
How the output should look like:
Initial of the first name is: Y
The last name is: Person
The age is: 18
You could read the whole file into a string variable, then use slice notation to get parts of it.
with read_file = open(file_name, read_mode):
line = read_file.read().strip()
initial = line[0]
last_name = line[1:7]
age = int(line[7:])
I am learning Python as a beginner and have a question that I couldn't figure out. I need to write functions to allow users to setup/give a file a name and then enter contents.
The error message I got is: "Str' object is not callable. I don't know how to fix this. Please could you help me out. Many thanks!
The code is as follows:
=========================================
WRITE = "w"
APPEND = "a"
fName = ""
def fileName(): #to define name of the file.
fName = input("Please enter a name for your file: ")
fileName = open(fName, WRITE)
return fileName
#now to define a function for data entry
dataEntry = ""
def enterData():
dataEntry = input("Please enter guest name and age, separated by a coma: ")
dataFile = open(fName, APPEND(dataEntry))
fName.append(dataEntry)
return dataFile
#to determine if it's the end of data entry
moreEntry = input("Anymore guest: Y/N ")
while moreEntry != "N":
enterData() #here to call function to repeat data entry
fName.close()
fileName()
enterData()
print("Your file has been completed!")
fileContents = fName.readline()
print(fileContents)
I ran the code and... I seeing the error as line 14
14 dataFile = open(fName, APPEND(dataEntry))
APPEND appears to be a str. It does not appear to be a function.
fName is not declared in this scope. Your function spacing is off. Maybe you meant to run the all the code in order rather than in parts?
As it is, fName is declared and defined once globally (line 4), declared and defined in function filename() (line 6).
fName is also referred to in the function (line 7) Called unsuccessfully in line 14
dataFile = open(fName, APPEND(dataEntry)) # fName has not been declared in function enterData()
I suspect your code would work if you reordered your lines and not use functions (due to references) Also, please close your files. EG
f = open ("somefile.txt", "a+")
...
f.close() #all in the same block.
Thanks for all the inputs. Much appreciated. I've reworked the code a bit, and to put all data entry into a list first, then try to append the list to the file. It works, to a certain extent (about 80%, perhaps!)
However, I now have another problem. When I tried to open the file to append the list, it says "No such file or directory" next to the code (line31): "myFile = open(fName, APPEND)". But I thought I declared and then let user define the name at the beginning? How should I make it work, please?
Thanks in advance again!
WRITE = "w"
APPEND = "a"
fName = ""
def fileName(): #to define name of the file.
fName = input("Please enter a name for your file: ")
fileName = open(fName, WRITE)
fileName.close()
return fileName
#now to define a function for data entry
dataEntry = ""
dataList = []
def enterData():
dataEntry = input("Please enter guest name and age, separated by a coma: ")
dataList.append(dataEntry)
return
fileName()
enterData()
#to determine if it's the end of data entry
moreEntry = input("Anymore guest: Y/N ")
if moreEntry == "Y":
enterData()
else:
print("Your file has been completed successfully!")
myFile = open(fName, APPEND)
myFile.append(dataList)
myFile.close()
fileContents = fName.readline()
print(fileContents)
I need to write a program that opens and reads a file and contains separate user-defined functions for counting the number of lines and words in the file e.g. linecount(), wordcount()etc. I drafted the below code, but I keep getting a name error that says "global name 'f' is not defined". f is a file handle that should be returned by the openfile() function. Any advise?
#open and read file
def openfile():
import string
name = raw_input ("enter file name: ")
f = open (name)
# Calculates the number of paragraphs within the file
def linecount():
openfile()
lines = 0
for line in f:
lines = lines + 1
return lines
#call function that counts lines
linecount()
Because f is local variable in openfile
def openfile():
import string
name = raw_input ("enter file name: ")
return open (name)
# Calculates the number of paragraphs within the file
def linecount():
f = openfile()
lines = 0
for line in f:
lines = lines + 1
return lines
or even shorter
def file_line_count():
file_name = raw_input("enter file name: ")
with open(file_name, 'r') as f:
return sum(1 for line in f)