I'm currently writing a simple text editor in python 3.8, I am unable to write the contents of the user input into a file though. When I open the text file in notepad++ a message pops up saying - "This file has been modified by another program, would you like to reload it?". I've tried writing the input to the file as an array but that does not work.
loop = True
#Getting file name
filename = input('Filename(Include file extensions) : ')
#Getting What To Write To File
while loop == True:
text = input('>> ')
if "EXIT" in text:
loop = False
while loop == False:
#writing to file
saveFile = open(filename, 'w')
saveFile.write(text)
saveFile.close()
Your loop structure is a bit off. There is no need for using "flag" variables. A more pythonic way is while True: ... break. So your code should look more like this:
#Getting file name
filename = input('Filename(Include file extensions) : ')
#Getting What To Write To File
while True:
text = input('>> ')
if "EXIT" in text:
break
#writing to file
with open(filename, 'w') as saveFile:
saveFile.write(text)
Of course this will only write the last input with the EXIT, so you might want to make text a list or a queue to perform as a buffer, or just dump directly to the file:
#Getting file name
filename = input('Filename(Include file extensions) : ')
#Getting What To Write To File
with open(filename, 'w') as saveFile:
while True:
text = input('>> ')
saveFile.write(text)
if "EXIT" in text:
break
Related
I'm making a program that takes text from an input file, then you input a file where it copies the already existing file text. Then, I need to replace a few words there and print the count of how many of these words were replaced. This is my code so far, but since with loops close the newly created file, I have no idea how to open it back again for reading and writing and counting. This is my awful code so far:
filename=input("Sisesta tekstifaili nimi: ")
inputFile=open(filename, "r")
b=input("Sisesta uue tekstifaili nimi: ")
uusFail=open(b+".txt", "w+")
f=uusFail
with inputFile as input:
with uusFail as output:
for line in input:
output.write(line)
lines[]
asendus = {'hello':'tere', 'Hello':'Tere'}
with uusFail as infile
for line in infile
for src, target in asendus
line = line, replace(src, target)
lines.append(line)
with uusFail as outfile:
for line in lines:
outfile.write(line)
There are a lot of unnecessary loops in your code. when you read the file, you can treat it as a whole and count the number of occurrences and replace them. Here is a modified version of your code:
infile = input('Enter file name: ')
outfile = input('enter out file: ')
with open(infile) as f:
content = f.read()
asendus = {'hello':'tere', 'Hello':'Tere'}
my_count = 0
for src, target in asendus.items():
my_count += content.count(src)
content = content.replace(src, target)
with open(f'{outfile}.txt','w+' ) as f:
f.write(content)
You need to reopen the file in the second block of code:
with open(b+".txt", "r") as infile:
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())
I have a list of filenames: files = ["untitled.txt", "example.txt", "alphabet.txt"]
I also have a function to create a new file:
def create_file(file):
"""Creates a new file."""
with open(file, 'w') as nf:
is_first_line = True
while True:
line = input("Line? (Type 'q' to quit.) ")
if line == "q":
# Detects if the user wants to quuit.
time.sleep(5)
sys.exit()
else:
line = line + "\n"
if is_first_line == False:
nf.write(line)
else:
nf.write(line)
is_first_line = False
I want the list to update itself after the file is created. However, if I just filenames.append() it,
I realized that it would only update itself for the duration of the program. Does anybody know how to do this? Is this possible in Python?
"Is this possible in Python?" -> This has nothing to do with limitations of the language you chose to solve your problem. What you want here is persistence. You could just store the list of files in a text file. Instead of hardcoding the list in your code your program would then read the content every time it is run.
This code could get you started:
with open("files.txt") as infile:
files = [f.strip() for f in infile.readlines()]
print(f"files: {files}")
# here do some stuff and create file 'new_file'
new_file = 'a_new_file.txt'
files.append(new_file)
###
with open("files.txt", "w") as outfile:
outfile.write("\n".join(files))
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()
I have a text file which contains the following paragraph:
The above with statement will automatically close the file after the nested block of code. The above with statement will automatically close the file after the nested block of code. The above with statement will automatically close the file after the nested block of code.
The above with statement will automatically close the file after the nested block of code without.
Now, I would like to modify the file by separating the individual lines for the paragraph, and save it in the same text file as the following:
The above with statement will automatically close the file after the nested block of code.
The above with statement will automatically close the file after the nested block of code.
The above with statement will automatically close the file after the nested block of code.
The above with statement will automatically close the file after the nested block of code without.
I was able to do it, but it was bit complicated. My code is as follows:
try-1
file = open("file_path")
content = file.read()
file.close()
file = open("file_path", 'w')
a = content.replace('. ', '.\n')
file.write(a)
file.close()
try-2
file = open("file_path")
contents = file.readlines()
file.close()
b = []
for line in contents:
if not line.strip():
continue
else:
b.append(line)
b = "".join(b)
file = open("file_path", 'w')
file.write(b)
file.close()
I opened the file twice to read and twice to write, is there any better way to separate the line from a paragraph from a text file, and writing it to the same text file?
You can do:
with open('filepath', 'r') as contents, open('filepath', 'w') as file:
contents = contents.read()
lines = contents.split('. ')
for index, line in enumerate(lines):
if index != len(lines) - 1:
file.write(line + '.\n')
else:
file.write(line + '.')
You can use seek method of files to jump in current file:
f.seek(offset, from_what)
And if you want to use file for write and read use option r+:
file = open("file_path", 'r+')
You also can skip step with readlines and use file iteration. Code should be:
file = open("file_path", "r+")
content = file.read()
a = content.replace('. ', '.\n')
file.seek(0)
file.write(a)
file.seek(0)
b = []
for line in file:
if not line.strip():
continue
else:
b.append(line)
b = "".join(b)
file.seek(0)
file.write(b)
file.close()