I am trying to create a todo list in python - python

the code should take what i worte in the input and add it to the txt file but i get an error because of the path please take a look.
main = input("What Task Would You Like To Add? > ")
f = open("C:\tdl\tdlp\MyToDoList.txt", "w")
f.write("content added")
f.close()
f = open("MyToDoList.txt", "r")
print(f.read())
I have tried replacing file formats and paths

Related

How to add numbers to a file

I'm a beginner at Python and I just learned about opening files, reading files, writing files, and appending files.
I would I like to implement this to a little project that I'm making that asks for the user's name and appends it to a txt file named "HallOfFame.txt"
try:
infile = open('HallOfFame.txt', 'r')
file_contents = infile.read()
print(file_contents)
infile.close()
except:
FileNotFoundError
print("No Human Has Ever Beat Me... mwah-ha-ha-ha!")
name_file = open("HallOfFame.txt", 'a')
name_record = input("Please enter your name: ")
name_file.write(str(name_record) + '\n')
name_file.close()
Everytime someone adds their name, I'd like it to become something like this:
Vix
Mike
Valerie
Something similar like that (above) where they have to run the program again to see the Hall of Fame.
Thank you!
I can understand your question. you can try using the JSON module and do something like this.
import json
list = [1, "Vix"]
with open ('HallOfFame.txt', 'w') as filehandle:
json.dump(list, filehandle)
here you can update the list every time you get input. and write it to the text file. but the appearance will look like this.
[1, "Vix"]
[2, "Mike"]
[3, "Valerie"]
count = 0
try:
infile = open('HallOfFame.txt', 'r')
file_contents = infile.readlines()
if len(file_contents) != 0:
print("\nHall of Fame")
for line in file_contents:
count += 1
print("{}. {}".format(count, line.strip()))
print()
infile.close()
except:
FileNotFoundError
print("No Human Has Ever Beat Me... mwah-ha-ha-ha!")
name_file = open("HallOfFame.txt", 'a')
name_record = input("Please enter your name: ")
name_file.write(str(name_record) + "\n")
name_file.close()

Can't Append to the File

I'm trying to write this program where if the user opens an existing file, they have the option to either read, start over, or append to it, but the append option isn't working. Why is that?
from sys import argv
file = input("Please open a file: ")
try:
file = open(file, "r+")
choice = input("""
What would you like to do with this file?
A) Read file
B) Delete file and start over
C) Append file
""").lower().rstrip()
if choice in "a":
print(file.read())
elif choice in "b":
print("What would you like to write?")
file.write(input())
elif choice in "c":
file = open(file, "a")
print("What would you like to write?\n")
file.write(input())
except:
print("This is a new file.\n")
file = open(file, "w")
print("What would you like to save in this file?")
file.write(input())```
The problem with your code is that you are assigning the variable file to the input of the user in input("Please open a file: "), but right after this you assign it to be the txt file in file = open(file, "r+").
So, when you write file = open(file, "a"), the compiler is reading file not as the user input, but the opened txt file.
What you should do is to give different names to the different variables
from sys import argv
filename = input("Please open a file: ")
try:
file = open(filename, "r+")
choice = input("""
What would you like to do with this file?
A) Read file
B) Delete file and start over
C) Append file
""").lower().rstrip()
if choice in "aA":
print(file.read())
elif choice in "bB":
print("What would you like to write?")
file.write(input())
elif choice in "cC":
file.close()
file = open(filename, "a")
print("What would you like to write?\n")
file.write(input())
except:
print("This is a new file.\n")
file = open(file, "w")
print("What would you like to save in this file?")
file.write(input())
UPDATE
As OneLiner said in the comments, you should always close the files after opening them. This can be easily done by using, as he said, with open(filename, "a") as file:. Besides that, I noticed two more things.
First, you shouldn't use except alone, because if I try, for example, to press ctrl+c, it will fall into this exception. What you should write instead is except FileNotFoundError, so that if there is no such file, this exception will be raised.
The second thing I noticed is that you are using the name file as the name of a variable. The problem is that file is already being used in python for another thing, so it would be better to use another name. In that case the code would be:
from sys import argv
filename = input("Please open a file: ")
try:
with open(filename, "r+") as file_txt:
pass
choice = input("""
What would you like to do with this file?
A) Read file
B) Delete file and start over
C) Append file
""").lower().rstrip()
if choice == "a":
with open(filename, "r") as file_txt:
print(file_txt.read())
elif choice == "b":
content = input("What would you like to write?\n")
with open(filename, "w") as file_txt:
file_txt.write(content)
elif choice == "c":
with open(filename, "a") as file_txt:
content = input("What would you like to write?\n")
file_txt.write(content)
except FileNotFoundError:
print("This is a new file.\n")
with open(filename, "w") as file_txt:
content = input("What would you like to save in this file?\n")
file_txt.write(content)
Using "r+" allows you to read and write, but the pointer is at the beginning, meaning that "appending" doesn't actually exist. If I'm not mistaken, there's no way to open a file for reading, writing, and appending, because there's no way to move the pointer along the file.
To get around this, I would suggest opening the file separately in each if clause.
If the person wants to read the file, then open it using "r".
If the person wants to write to the file, then open it using "w", and if the person wants to append to it, then open it using "a". More options, such as combinations of two can be found here.
The code:
try:
#removed:
#file = open(file, "r+")
choice = input("""
What would you like to do with this file?
A) Read file
B) Delete file and start over
C) Append file
""").lower().rstrip()
if choice in "a":
file = open(file, "r")
print(file.read())
elif choice in "b":
file = open(file, "w")
print("What would you like to write?")
file.write(input())
elif choice in "c":
file = open(file, "a")
print("What would you like to write?\n")
file.write(input())
except:
print("This is a new file.\n")
file = open(file, "w")
print("What would you like to save in this file?")
file.write(input())

How can I open and read an input file and print it to an output file in Python?

So how can I ask the user to provide me with an input file and an output file?
I want the content inside the input file provided by the user to print into the output file the user provided. In this case, the user would put in this
Enter the input file name: copyFrom.txt
Enter the output file name: copyTo.txt
inside the input file is just the text "hello world".
Thanks. Please keep it as simple as you can if possible
If you just want to copy the file, shutil’s copy file does the loop implicitly:
import os
from shutil import copyfile
openfile = input('Enter the input file name:')
outputfile = input('Enter the output file name:')
copyfile(openfile, outputfile)
This this post How do I copy a file in Python? for more detail
Here is an example that should work in Python3. The input and output file names would need to include the full path (i.e. "/foo/bar/file.txt"
import os
input_file = input('Enter the input file name: ')
output_file = input('Enter the output file name: ')
def update_file(input_file, output_file):
try:
if os.path.exists(input_file):
input_fh = open(input_file, 'r')
contents = input_fh.readlines()
input_fh.close()
line_length = len(contents)
delim = ''
if line_length >= 1:
formatted_contents = delim.join(contents)
output_fh = open(output_file, 'w')
output_fh.write(formatted_contents)
output_fh.close()
print('Update operation completed successfully')
except IOError:
print(f'error occurred trying to read the file {input_fh}')
update_file(input_file, output_file)
You can do this...
import os
openfile = input('Enter the input file name:')
outputfile = input('Enter the output file name:')
if os.path.isfile(openfile):
file = open(openfile,'r')
output = open(outputfile,'w+')
output.write(file.read())
print('File written')
exit()
print('Origin file does not exists.')
To input the input-file and output-file names, simply use the input(s) function where s is the input message.
To get the "content inside the input file provided by the user to print into the output file," that would mean reading the input file and writing the read data into the output file.
To read the input file, use f = open(input_filename, 'r'), where the first argument is the filename and the second argument is the open mode where 'r' means read. Then letting readtext be the read text information of the input file, use readtext = f.read(): this returns the entire text content of f.
To output the read content to the output file, use g = open(output_filename, 'w'), noting that now the second argument is 'w', meaning write. To write the data, use g.write(readtext).
Please note that an exception will be raised if the input file is not found or the output file is invalid or not possible as of now. To handle these exceptions, use a try-except block.
This is effectively a file-copying operation in Python. shutil can serve as a useful alternative.
First you have to read the file and save it to some variable (here rd_data):
if os.path.exists(input_file_name):
f = open(input_file_name,"r")
rd_data = f.read()
f.close()
Then you have to write the variable to other file:
f = open(output_file_name,"w")
f.write(rd_data)
f.close()
The full code is given below:
import os
input_file_name = input("Enter file name to read: ")
output_file_name = input("Enter file name to write: ")
if os.path.exists(input_file_name):
f = open(input_file_name,"r")
rd_data = f.read()
f.close()
f = open(output_file_name,"w")
f.write(rd_data)
f.close()

How to make a continuously upcounting txt file?

I am trying to make a code block that creates a series of .txt file names. It will open a new file and prompt the user to enter text for the file, continuing until the user doesn't want any more files.
How do I get it to create a series of file names such as file1.txt, file2.txt, file3.txt, etc. ?
filenum = 1
while # getting input from user
outfile = open ("userfile" + str(filenum), 'w')
filenum += 1
# rest of your loop
Assuming you do know in advance how many files are required you can pass a start value to the function range()
fnum = 10
fname = 'file'
ext = '.txt'
for i in range(1, fnum + 1):
with open("{fname}{fnum}{ext}".format(fname=fname, fnum=i, ext=ext), 'w') as f:
# OR for Python 3.6+
# with open(f'{fname}{i}{ext}', 'w') as f:
print(input('User Input: '), file=f)

Cannot read Excel chart properly with intended line of code

So this might be a simple solution but I can't seem to come up with it. When I use the following code I can open the file, read through it and do all the necessary functions, but if I use the commented line instead of the one underneath it gives me an error at line r = L[15] like it can't read it properly anymore. What can I do about this? If more code is needed I can provide it. Thanks!
def open_file():
while True:
file = input("Enter a file name: ")
try:
open(file)
return file
except FileNotFoundError:
print("Error. Please try again.")
print()
def read_file():
#fp = open_file()
fp = open("Texas_death_row.csv")
csv_fp = csv.reader(fp)
data = []
for L in csv_fp:
r = L[15]
g = L[16]
v = L[27]
T = (r,g,v)
my_list.append(T)
return data
Your open_file function is returning the variable file, that contains the string containing the filename, not the file object (file descriptor) which is what you can read and whatnot.
You should try something like this:
def open_file():
while True:
file = input("Enter a file name: ")
try:
f = open(file)
return f # Return the "file object", not the file name
except FileNotFoundError:
print("Error. Please try again.")
print()
PS: When you're dealing with files, don't forget to close them when you're done with them.

Categories

Resources