Opening two filenames - python

I want to build a function that asks the user to type in a source filename and a destination filename; opens the files, loops through the contents of the source file line-by-line, writing each one to the destination file; and then closes both files. Make sure that all work with the files happens inside of a try block. If an IOError occurs, the script should print a message saying that there was an error working with one of the files and ask the user to enter in the filenames again. Here is what I have so far:
while True:
try:
file = open(filename)
line = file.readline()
while line != "":
print(line)
line = file.readline()
file.close()
break
except IOError:
print("There was a problem accessing file '" + filename + "'." + \
"Please enter a different filename.")
filename = input("> ")
However, I don't know how to ask the user for 1.) user input 2.) ask for both the filename and destination filename 3.) writing each source to the destination file. Help if you can..

There are some things that I could show you.
To do input
inputFileName = str(raw_input("Enter the input file: "))
outputFileName = str(raw_input("Enter the output file name: "))
Also, to learn about using files you can check out a good tutorial here.
Finally, you shouldn't be running your file = open(filename) in a while loop. Only the reading of the lines should be done in a loop.

You only need to add a little to your existing code:
in_filename = input('input from filename: ')
ou_filename = input('output to filename: ')
while True:
try:
infile = open(in_filename)
oufile = open(ou_filename, 'w')
line = infile.readline()
while line != "":
# print(line)
oufile.write(line)
line = infile.readline()
infile.close()
oufile.close()
break
except IOError:
print("There was a problem accessing file '" + in_filename + "'." + \
"or maybe '" + ou_filename + "'." + \
"Please enter different filenames.")
in_filename = input('input from filename: ')
ou_filename = input('output to filename: ')
Of course, there are many things left to improve here -- for example, by insisting that everything be within a single try/except statement, you don't know, in the error message, which of the two files gave problems.
But at least I've added the in_ and ou_ prefixes to distinguish input from output, and avoided using the built-in name file as a variable name (trampling over built-in names is a notorious trap for beginners, which gives no problems... until it suddenly does:-).

1.2) You can get the user input and both filename by sys.argv sys.argv.
3) File operation. file

Related

How can i delete a couple lines of text that I inputted into a text file in python?

I am making a small simple password manager in python. I have the functions of creating an account which has 3 inputs, Username, Password, and Website. I have a function to view all the accounts which shows the contents of the file info.txt where all that information goes. Im trying to create a function to delete an entry but im not sure how to make the function delete all the lines of information associated with the Username. I want an input asking "Which account to delete" you put the username, and it will delete all information associated with the username in info.txt
Code:
import os.path #Imports os module using path for file access
def checkExistence(): #Checking for existence of file
if os.path.exists("info.txt"):
pass #pass is used as a placeholder bc if no code is ran in an if statement and error comes.
else:
file = open("info.txt", "w") #creates file with name of info.txt and W for write access
file.close()
def appendNew():
#This function will append a new password in the txt file
file = open("info.txt", "a") #Open info.txt use a for appending IMPORTANT: opening a file with w for write will write over all existing data
userName = input("Enter username: ")
print(userName)
os.system('cls')
password = input("Enter password: ")
print(password)
os.system('cls')
website = input("Enter website: ")
print(website)
os.system('cls')
print()
print()
usrnm = "Username: " + userName + "\n" #Makes the variable usrnm have a value of "Username: {our username}" and a new line
pwd = "Password: " + password + "\n"
web = "Website: " + website + "\n"
file.write("----------------------------------\n")
file.write(usrnm)
file.write(pwd)
file.write(web)
file.write("----------------------------------\n")
file.write("\n")
file.close()
def readPasswords():
file = open("info.txt", "r") #Open info.txt with r for read
content = file.read() # Content is everything read from file variable (info.txt)
file.close()
print(content)
checkExistence()
while True:
choice = input("Do you want to: \n 1. Add account\n 2. View accounts\n 3. Delete account\n")
print(choice)
if choice == "1":
os.system('cls')
appendNew()
elif choice == "2":
os.system('cls')
readPasswords()
elif choice == "3":
os.system('cls')
else:
os.system('cls')
print("huh? thats not an input.. Try again.\n")
I tried making a delete account function by deleting the line which matched the username. My only problem is that it only deletes the line in info.txt with the username, but not the password and website associated with that username.
Firstly, you're using the wrong tool for the problem. A good library to try is pandas, using .csv files (which one can think of as pore program oriented excel files). However, if you really want to use the text file based approach, your solution would look something like this:
with open(textfile, 'r+') as f:
lines = [line.replace('\n', '') for line in f.readlines()]
# The above makes a list of all lines in the file without \n char
index = lines.index(username)
# Find index of username in these lines
for i in range(5):
lines.pop(index)
# Delete the next five lines - check your 'appendNew' function
# you're using five lines to write each user's data
print(lines)
f.write("\n".join(lines))
# Finally, write the lines back with the '\n' char we removed in line 2
# Here is your readymade function:
def removeName(username):
with open("info.txt", 'r+') as f:
lines = [line.replace('\n', '') for line in f.readlines()]
try:
index = lines.index(username)
except ValueError:
print("Username not in file!")
return
for i in range(5):
lines.pop(index)
print(lines)
f.write("\n".join(lines))
# Function that also asks for username by itself
def removeName_2():
username = input("Enter username to remove:\t")
with open("info.txt", 'r+') as f:
lines = [line.replace('\n', '') for line in f.readlines()]
try:
index = lines.index(username)
except ValueError:
print("Username not in file!")
return
for i in range(5):
lines.pop(index)
print(lines)
f.write("\n".join(lines))
# Usage:
removeName(some_username_variable)
removeName_2()
Again, this is a rather clunky and error prone approach. If you ever change the format in which each user's details are stored, your would have to change the number of lines deleted in the for loop. Try pandas and csv files, they save a lot of time.
If you're uncomfortable with those or you're just starting to code, try the json library and .json files - at a high level they're simple ways of storing data into files and they can be parsed with the json library in a single line of code. You should be able to find plenty of advice online about pandas and json.
If you're unable to follow what the function does, try reading up on try-except blocks and function parameters (as well as maybe global variables).

How can I include file name error handling with this piece of code?

I am required to include some form of error handling when the user inputs the file name such that if they put a file name which is not within the programs directory then it will appear with an error message. This is the code at the moment:
board = []
fileinput = input("Please enter your text file name:")
filename = fileinput + ".txt"
file = open(filename, "r+")
for lines in file:
board.append(list(map(int,lines.split())))
I'm not sure where to include the try/except as if I include it like this:
board = []
fileinput = input("Please enter your text file name:")
filename = fileinput + ".txt"
try:
file = open(filename, "r+")
except:
print("Error: File not found")
for lines in file:
board.append(list(map(int,lines.split())))
Then I get the following error:
line 28, in
for lines in file:
NameError: name 'file' is not defined
I know there probably is a very simple solution but I am struggling with wrapping my head around it.
You should include all lines which may occur error under try, so:
board = []
fileinput = input("Please enter your text file name:")
filename = fileinput + ".txt"
try:
file = open(filename, "r+")
for lines in file:
board.append(list(map(int,lines.split())))
except:
print("Error: File not found")
The way you presented, the program try to ignore error and go over, which ends with NameError: name 'file' is not defined
The second problem in your case would be with scope - file is local variable in try and you call it outside of scope.

Using while true function allow multiple correct user input

I have used a while True function to allow a user to open a monthly excel file. Is there a way to allow a user to be able to open 12 other files that are monthly reports while still handling incorrect file choice?
while True:
file = input("select file name: ")
if not file == "July":
file - input("unknown file, hit enter to select file name")
continue
else:
df = pd.read_excel('filename here')
break
You use os.path.exists to check that a file exists. Beyond that, there are other tests you might want to do - you might want to check the file extension, or make sure that it is in a particular directory, or whatever else correct user input means. If you're checking file extensions, you can do worse than to use pathlib.Path, which also has an exists() method.
Simple example with os.path.exists():
import os.path
while True:
file = input("select file name: ")
if not os.path.exists(file):
file - input("File does not exist, hit enter to select file name")
continue
else:
df = pd.read_excel(file)
break
You could make the code a lot more readable and concise if you put the conditional inside the while loop head (like Guido intended):
filename = input("select file name: ")
while not os.path.exists(filename):
print("Error - file '%s' does not exist." % filename)
filename = input("select file name: ")
df = pd.read_excel(filename)
If I correctly understand, you can store all files' names in some variable and store all open files in another one. In this case, you need to break only when a user opened all 12 files.
Should be smth like this:
file_names = ("July", "August")
open_files = []
while True:
file = input("select file name: ")
if file not in file_names:
input(
"{file} - unknown file, hit enter to select file name".format(file)
)
continue
elif file in open_files:
file - input("{file} is already opened, try another one".format(file))
else:
df = pd.read_excel(file)
open_files.append(file)
if len(open_files) == 12:
break

How to write and read to a file in python?

Below is what my code looks like so far:
restart = 'y'
while (True):
sentence = input("What is your sentence?: ")
sentence_split = sentence.split()
sentence2 = [0]
print(sentence)
for count, i in enumerate(sentence_split):
if sentence_split.count(i) < 2:
sentence2.append(max(sentence2) + 1)
else:
sentence2.append(sentence_split.index(i) +1)
sentence2.remove(0)
print(sentence2)
outfile = open("testing.txt", "wt")
outfile.write(sentence)
outfile.close()
print (outfile)
restart = input("would you like restart the programme y/n?").lower()
if (restart == "n"):
print ("programme terminated")
break
elif (restart == "y"):
pass
else:
print ("Please enter y or n")
I need to know what to do so that my programme opens a file, saves the sentence entered and the numbers that recreate the sentence and then be able print the file. (im guessing this is the read part). As you can probably tell, i know nothing about reading and writing to files, so please write your answer so a noob can understand. Also the one part of the code that is related to files is a complete stab in the dark and taken from different websites so don't think that i have knowledge on this.
Basically, you create a file object by opening it and then do read or write operation
To read a line from a file
#open("filename","mode")
outfile = open("testing.txt", "r")
outfile.readline(sentence)
To read all lines from file
for line in fileobject:
print(line, end='')
To write a file using python
outfile = open("testing.txt", "w")
outfile.write(sentence)
to put it simple, to read a file in python, you need to "open" the file in read mode:
f = open("testing.txt", "r")
The second argument "r" signifies that we open the file to read. After having the file object "f" the content of the file can be accessed by:
content = f.read()
To write a file in python, you need to "open" the file in write mode ("w") or append mode ("a"). If you choose write mode, the old content in the file is lost. If you choose append mode, the new content will be written at the end of the file:
f = open("testing.txt", "w")
To write a string s to that file, we use the write command:
f.write(s)
In your case, it would probably something like:
outfile = open("testing.txt", "a")
outfile.write(sentence)
outfile.close()
readfile = open("testing.txt", "r")
print (readfile.read())
readfile.close()
I would recommend follow the official documentation as pointed out by cricket_007 : https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

How to check if a file equals a variable in python?

I am a novice with Python I suppose, and I was wondering if there was a way to read a file and then check if user's input equalled that file's text.
I've been trying to create a password program without having to show the password/variable in the program. If there's another way to do this without doing .read() and things (if they don't work) then I would be happy to hear those suggestions!
This should do it:
# The path to the file
filepath = 'thefile.txt'
# This is how you should open files
with open(filepath, 'r') as f:
# Get the entire contents of the file
file_contents = f.read()
# Remove any whitespace at the end, e.g. a newline
file_contents = file_contents.strip()
# Get the user's input
user_input = input('Enter input: ')
if user_input == file_contents:
print('Match!')
else:
print('No match.')

Categories

Resources