reading, writing, appending, and deleting files in python - python

here's my code, i could use your help.
My program is supposed to accept data input, create new text files,read and write into text files, append text into already existing text files, truncate and delete files.
Now the problem i have with my program is that the the part of the code that is supposed to append text, truncate the content of a text file and delete a text file is not working and the program does not return any errors during run time.
import os
from sys import argv
filename = argv
def menu():
holder = input("enter 1 to create new file or 2 to use existing ones\n")
if holder == 1:
dam = raw_input("Enter name of new text file:\n")+'.txt'
textfile = open(dam, 'w+')
happ = raw_input("\nPlease enter record into your new file\n\n")
textfile.write(happ)
textfile.close()
print "*******************"
print "*******************\n"
print "To view the content of your new file, enter 'yes' otherwise enter 'no' to exit"
gett = raw_input()
if gett == 'yes':
print "*******************"
print "\nyour inputted record is>>>\n"
display = open(dam)
print(display.read())
print'\n'
menu()
elif gett == 'no':
print ("\nOk, see you later. Have a nice day!")
print'\n'
menu()
else:
print "\nyou have entered a wrong input"
print '\n'
menu()
elif holder == 2:
filename = raw_input("Enter name of file:\n")+'.txt'
entry = raw_input("Press 7 to append text into this file, 8 to truncate the content of this file, or 9 to delete this file : ")
if entry == 7:
print ("Displayed below is the content of your file, continue to append more text at the bottom of the file.(text is limited to 3 lines)\n")
textfiles = open(filename, 'a+')
print (textfiles.read())
line1 = raw_input( )
line2 = raw_input( )
line3 = raw_input( )
print "\nSaving..."
textfiles.write(line1)
textfiles.write('\n')
textfiles.write(line2)
textfiles.write('\n')
textfiles.write(line3)
textfiles.write('\n')
print "\nSaved!"
textfiles.close()
elif entry == 8:
textfiles = open(filename, 'w')
print "Truncating the file..."
textfiles.truncate()
print "Done, truncated."
textfiles.close()
right = raw_input("Do you want to write into this file? Y/N : ")
if right == 'Y':
textfiles = open(filename, 'a+')
print "text is limited to 3 lines"
line1 = raw_input('\n')
line2 = raw_input()
line3 = raw_input()
print "\nSaving..."
textfiles.write(line1)
textfiles.write('\n')
textfiles.write(line2)
textfiles.write('\n')
textfiles.write(line3)
textfiles.write('\n')
print "\nSaved!"
textfiles.close()
else:
print "Ok have a nice day"
elif entry == 9:
print "Deleting the file..."
try:
os.remove(filename)
except OSError, e: #if failed, report it back to the user
print ("Error: %s - %s." % (e.filename, e.strerror))
print "Done, deleted."
else:
print "Error! wrong entry"
print '\n'
menu()
else:
print "\nyou have entered a wrong input"
print '\n'
menu()
menu()
This is the output it gives
enter 1 to create new file or 2 to use existing ones
2
Enter name of file:
test
Press 7 to append text into this file, 8 to truncate the content of this file, or 9 to delete this file : 8
Error! wrong entry
enter 1 to create new file or 2 to use existing ones
ANY HELP ON HOW TO MAKE THIS WORK?

You are using the function raw_input() for your variable entry at the line
entry = raw_input("Press 7 to append text into this file, 8 to truncate the content of this file, or 9 to delete this file : ")
Refering to the documentation of python2 (https://docs.python.org/2/library/functions.html#raw_input), the function raw_input return a String.
After, you are testing your variable entry against integer values. Since a String never equals an int, the test won't work. And your code fall in the last condition block which is "wrong input"
To fix this issue, you should use the input function like you did at the begining of your code (https://docs.python.org/2/library/functions.html#input):
entry = input("Press 7 to append text into this file, 8 to truncate the content of this file, or 9 to delete this file : ")
or cast entry to int
entry = int(raw_input("Press 7 to append text into this file, 8 to truncate the content of this file, or 9 to delete this file : "))

Related

(Python) How to test if a string is contained in a file

I'm trying to create a username database and the code all runs how I want except for when I try to test if the file contains the entered text. For some reason it just runs past the elif statement and hits the else statement if it already exists in the text.
Here is the full code:
class username:
def add():
while(True):
file = open("usernames.txt", 'r+')
names = list(file.read())
entered = str(input("Username: "))
if len(entered) == 0:
print("Please enter a valid username\n")
continue
elif not(entered.isalpha):
print("Please enter a valid username\n")
continue
elif entered in file.read():
print("That name is already in use.",
"\nPlease enter a different username. \n")
continue
elif len(entered) < 4 or len(entered) > 12:
print("Please enter a username with 4-12 characters.\n")
continue
else:
print(entered)
file.close()
add = open("usernames.txt", 'a+')
plusnewline = entered + "\n"
add.write(plusnewline)
add.close()
break
def list():
file = open("usernames.txt","r+")
names = file.read()
print(names)
file.close()
username.add()
username.list()
edit: Answered by Shadow:
Changed:
names = list(file.read())
to:
names = file.read()
and changed:
elif entered in file.read():
to:
elif entered in names:
You can only call file.read once - after that it's already read.
Either use file.seek(0) to go back to the start of the file (which will allow you to read it again), or cache the contents in a variable so that you can reuse it (that is, refer to your names variable)

How to write "No file ends with" a user-defined extension

I was wondering if there was a way to tell the user that no file in a directory they specified has the file extension they are looking for. The only way I could think of uses an if/else, but would be tripped up if any other file extension exists in the directory. I was able to find something but it was bash: Listing files in a directory that do not end with vXXX and not exactly what I was looking for.
Here is an example of a directory:
out-30000000.txt.processed
out-31000000.txt.processed
out-32000000.txt.processed
out-33000000.txt.processed
out-34000000.txt.processed
nope.csv
If I use the following code:
def folder_location():
location = raw_input("What is the folder containing the data you like processed located? ")
#location = "C:/Code/Samples/Dates/2015-06-07/Large-Scale Data Parsing/Data Files"
if os.path.exists(location) == True: #Tests to see if user entered a valid path
print "You entered:",location
if raw_input("Is this correct? Use 'Y' or 'N' to answer. ") == "Y":
print ""
file_extension(location)
else:
folder_location()
else:
print "I'm sorry, but the file location you have entered does not exist. Please try again."
folder_location()
def file_extension(location):
file_extension = raw_input("What is the file type (.txt for example)? ")
print "You entered:", file_extension
if raw_input("Is this correct? Use 'Y' or 'N' to answer. ") == "Y":
print ""
each_file(location, file_extension)
else:
file_extension(location)
def each_file(location, file_extension):
try:
column = (raw_input("Please enter column name you want to analyze: ")) #Using smcn
print "You entered:",column
if raw_input("Is this correct? Use 'Y' and 'N' to answer. ") == "Y":
print ""
sort_by(location,file_extension,column)
else:
each_file(location,file_extension)
except TypeError:
print "That is not a valid column name. Please try again."
each_file(location,file_extension)
def sort_by(location, file_extension, column):
content = os.listdir(location)
for item in content:
if item.endswith(file_extension):
data = csv.reader(open(os.path.join(location,item)),delimiter=',')
col_position = get_columnposition(data.next(),column)
to_count = sorted(data, key=operator.itemgetter(col_position))
count_date(to_count, location)
else:
print "No file in this directory ends with " + file_extension
I get:
No file in this directory ends with .processed
and then the rest of my output (code not posted here).
Is there a way for me to say (I'm going to put it in a code block just to show how it works in my mind):
def file_extension(location):
file_extension = raw_input("What is the file type (.txt for example)? ")
print "You entered:", file_extension
if raw_input("Is this correct? Use 'Y' or 'N' to answer. ") == "Y":
print ""
each_file(location, file_extension)
else:
file_extension(location)
def each_file(location, file_extension):
try:
column = (raw_input("Please enter column name you want to analyze: ")) #Using smcn
print "You entered:",column
if raw_input("Is this correct? Use 'Y' and 'N' to answer. ") == "Y":
print ""
sort_by(location,file_extension,column)
else:
each_file(location,file_extension)
except TypeError:
print "That is not a valid column name. Please try again."
each_file(location,file_extension)
def sort_by(location, file_extension, column):
content = os.listdir(location)
for item in content:
if item.endswith(file_extension):
data = csv.reader(open(os.path.join(location,item)),delimiter=',')
col_position = get_columnposition(data.next(),column)
to_count = sorted(data, key=operator.itemgetter(col_position))
count_date(to_count, location)
if no item.endswith(file_extension):
print "No file in this directory ends with " + file_extension
Any help would be greatly appreciated. If it would help, I could edit in the rest of my code I have at the moment.
Thanks!
Your logic should be the following:
Ask for the directory
Ask for the extension
Check if any file ends with that extension
If there is at least one file, then ask for the column
To make all this easier, use csv and glob:
import glob
import csv
import os
directory = input('Please enter the directory: ')
extension = input('Please enter the extension (.txt, .csv): ')
files = list(glob.glob(os.path.join(directory, extension)))
if not files:
print('Sorry, no files match your extension {} in the directory {}'.
format(extension, directory))
else:
for file_name in files:
col = input('Enter the column number for {}'.format(file_name))
with open(file_name, 'r') as thefile:
reader = csv.reader(thefile, delimiter=',')
for row in reader:
try:
do_something(row[col])
except IndexError:
print('Column {} does not exist'.format(col))

Issue with "w" to output and a loop in python3

I have an issue with the program i'm currently writing.
Here's the code:
def main():
print ("This program let you create your own HTML-page,\nwith the necessary tags allready included")
t = ("<!DOCTYPE html>", "<html>", " <head>", " </head>", "<body>", "</html>") #Spaces for the indentation in the HTML-code.
menu = input("Press 1 to enter the file name for the html-page\nPress 2 to enter title for the HTML-page\nPress 3 to start entering code in body ")
while True:
if menu == "1":
name = input("Enter the name for your HTML-page: ")
#with open(name + ".html", 'w') as doc:
#Here is the first problem, indenterror if uncommented, otherwise elif gets syntax error.
#And this is crucial to get the code into the HTML-document.
#The error without (with open(name + ".html", 'w') as doc:) will be "global name "doc" is not defined".
menu = input("Press 2 to enter title for the HTML-page\nPress 3 to start entering code in body ")
elif menu == "2":
print (t[0], file=doc) #<!DOCTYPE html>
print (t[1], file=doc) #<html>
print (t[2], file=doc) #<head>
title = input("Enter your title here: ")
doc.write(title)
print (t[3], file=doc) #</head>
menu = input("Press 3 to start entering code in body ")
elif menu == "3":
print(t[4], file=doc) #<body>
code = input("Type </body> to finish your html-page and to close the program.\nEnter your code for body below:\n")
doc.write('{0}\n'.format(code)) #For newline to get the HTML-code cleaner.
while code != "</body>":
code = input("")
doc.write('{0}\n'.format(code))
if code == "</body>":
print ("Congratulations! You have successfully created your own HTML-page by using this python program.")
print (t[5], file=doc) #</html>
#somewhere in the loop above is the second error, I want the </body> to end the program,
#but it loops line 25 (code = input("Type </body> to finish your html-page and to close the program.\nEnter your code for body below:\n"))
main ()
Now to the issues. As you can see I'm trying to write a menu for the user to choose from 3 different tasks. Everything they do is supposed to output to a .html document.
I have commented my problems in the code as you can see.
I can't figure out how to get the with open(name + ".html", 'w') as doc: without the indentation for elif getting messed up, or I simply get an syntax error for elif.
The second problem is my loop at the end. I want the command to exit the program as it also output the correct ending code for the .html document, but it loops code = input("Type </body> to finish your html-page and to close the program.\nEnter your code for body below:\n") and I can't figure that out aswell.
def main():
(...)
while True:
if menu == "1":
name = input("Enter the name for your HTML-page: ")
doc = open(name + ".html", 'w')
menu = input("Press 2 to enter title for the HTML-page\nPress 3 to start entering code in body ")
(...)
doc.close()
main ()
You can open a file like so: doc = open(name + ".html", 'w'), but don't forget to close it when you're done with it, like so doc.close().
Here is a simple file-opening function. Of course, it needs to be tweaked for your specific needs. The "with" statement itself will close the file.
def cat(openfile): #Emulates the cat command used in the Unix shell#
with open(openfile) as file:
lines = file.readlines()
return ''.join(lines)
If you want to write to a file, use this function.
def write2file(openfile, WRITE): #openfile = filename to open #WRITE = the string you want to write to file
with open(openfile, 'w') as file:
file.write(str(WRITE))
To append/add text to a file:
def add2file(openfile, add):
with open(openfile, 'a') as file:
file.write(str(add))

Python (latest version) Syntax Error

I wrote this sample program that is meant to open a text file (database1.txt) from the computer, and display the results that are currently in the file. Then prompt the use if their name is in the document, if it is it should print the contents of the text file then close, otherwise it should prompt the user to enter their first name, then the program writes the name into the same text document, then prints the contents of the text file again so that the user can see the new added data. I have typed the code, and somehow it keeps saying I have a syntax error. I checked a few times and I cannot fix the error. I was wondering if someone could take a look and if they might be able to explain the error to me. Thank you
#This program reads/writes information from/to the database1.txt file
def database_1_reader ():
print('Opening database1.txt')
f = open('database1.txt', 'r+')
data = f.read()
print data
print('Is your name in this document? ')
userInput = input('For Yes type yes or y. For No type no or n ').lower()
if userInput == "no" or userInput == "n"
newData = input('Please type only your First Name. ')
f.write(newData)
f = open ('database1.txt', 'r+')
newReadData = f.read()
print newReadData
f.close()
elif userInput == "yes" or userInput == "ye" or userInput == "y"
print data
f.close()
else:
print("You b00n!, You did not make a valid selection, try again ")
f.close()
input("Presss any key to exit the program")
database_1_reader()
print is a function in py3.x:
print newReadData
should be :
print (newReadData)
Demo:
>>> print "foo"
File "<ipython-input-1-45585431d0ef>", line 1
print "foo"
^
SyntaxError: invalid syntax
>>> print ("foo")
foo
statements like this:
elif userInput == "yes" or userInput == "ye" or userInput == "y"
can be reduced to :
elif userInput in "yes"

Python: Problem closing files in a while loop

I've ran into an error while dealing with a while loop. I am able to input the number I want to run, and the results are written correctly to the corresponding .CSV. Once the section for that number is done running, it will ask if I want to try again with a new number. It runs the new numbers code and creates the new .CSV but the filesize stays at 0kb. I thought this has to do with closing the file once complete but I have written the f#.close() in there.
Ex: Choose number 1, code for #1 runs and saves .CSV correctly, choose Yes for another run and new number (#2), code #2 runs but does not correctly close thus not saving any info to the second CSV.
This happens regardless of which number I choose first or second. (ex: choose 3 first, 3 runs fine and saves fine. Then choosing 2 and runs but does not save correctly.)
Here is my current code:
f1 = file('1.csv', 'rb')
f2 = file('2.csv', 'rb')
f3 = file('3.csv', 'rb')
c1 = csv.reader(f1)
c2 = csv.reader(f2)
c3 = csv.reader(f3)
number = raw_input("Enter number: ")
while True:
if number == "1":
f4 = file('No_1_Results.csv', 'wb')
c4 = csv.writer(f4)
<snip> #do stuff here
print "Took ", time.time() - start, "seconds."
f4.close()
reset_answer = raw_input("Again? Type Y or N : ")
if reset_answer == ("n" or "N"):
print "Bye! from #1"
break
if reset_answer == ("y" or "Y"):
number = raw_input("Enter new number #: ")
continue
if reset_answer != ("n" or "N" or "y" or "Y"):
print "Y or N only allowed. Try again."
continue
if number == "2":
f5 = file('No_2_Results.csv', 'wb')
c5 = csv.writer(f5)
<snip> #do stuff here
print "Took ", time.time() - start, "seconds."
f5.close()
reset_answer = raw_input("Again? Type Y or N : ")
if reset_answer == ("n" or "N"):
print "Bye! from #2"
break
if reset_answer == ("y" or "Y"):
number = raw_input("Enter new number #: ")
continue
if reset_answer != ("n" or "N" or "y" or "Y"):
print "Y or N only allowed. Try again."
continue
if number =="3":
f6 = file('No_3_Results.csv', 'wb')
c6 = csv.writer(f6)
<snip> #do stuff here
print "Took ", time.time() - start, "seconds."
f6.close()
reset_answer = raw_input("Again? Type Y or N : ")
if reset_answer == ("n" or "N"):
print "Bye! from #3"
break
if reset_answer == ("y" or "Y"):
number = raw_input("Enter new number #: ")
continue
if reset_answer != ("n" or "N" or "y" or "Y"):
print "Y or N only allowed. Try again."
continue
if number is not "1" or "2" or "3":
print "Invalid number selected."
number = raw_input("Please choose a number: ")
continue
f1.close()
f2.close()
f3.close()
Note: Using Python 2.6 on Windows / still learning python -
It would be nice to know what you are exactly doing with the file descriptor you opened at the beginning of the loop (f1, f2, f3). Nevertheless I believe that the issue you have is related with the fact that you are trying to read twice from one of those file descriptors but you are not resetting their position when doing it. Take look at the following:
$ echo "Test reading from a file" >> test.out
$ python
>>> f1 = file('test.out')
>>> f1.readlines()
['Test reading from a file\n']
>>> f1.readlines()
[]
After reading from a file the file descriptor remembers your position form the last read. To solve your issue you would have to perform a seek and going to the beginnings of the file:
$ echo "Test reading from a file" >> test.out
$ python
>>> f1 = file('test.out')
>>> f1.readlines()
['Test reading from a file\n']
>>> f1.seek(0)
>>> f1.readlines()
['Test reading from a file\n']
I hope this is the issue you have, otherwise you should show the logic that you have when reading the file.
import csv
try:
inp = raw_input # Python 2.x
except NameError:
inp = input # Python 3.x
def processFile(infname, outfname, perRow):
with open(infname,'rb') as inf, open(outfname,'w') as outf:
incsv = csv.reader(inf)
outcsv = csv.writer(outf)
outcsv.writerows(perRow(row) for row in incsv)
print("{0} -> {1} successful".format(infname, outfname))
def doStuff(row):
# do stuff here
return row
def main():
while True:
name = inp('Enter next file name (or nothing to exit)')
if name.strip():
try:
processFile(name+'.csv', name+'_result.csv', doStuff)
except IOError, e:
print(e)
else:
print("Goodbye.")
break
if __name__=="__main__":
main()
Edit: after looking at your link to Python: Comparing two CSV files and searching for similar items I would continue with
def readMasterList():
res = {}
with open('masterlist.csv','rb') as inf:
incsv = csv.reader(inf)
head = incsv.next() # skip header row
for rownum,dat in enumerate(incsv):
res[tuple(dat)] = rownum
return res
masterList = readMasterList()
def doStuff(row, _ml=masterList):
key = (row[1], row[3])
try:
rownum = _ml[key]
row.append("FOUND in master list (row {0})".format(rownum))
except KeyError:
row.append("NOT FOUND in master list")
return row

Categories

Resources