I'm new at programming and i need help with converting first file to another file. The task is:
Write a program that asks the user for two filenames. The first one should mark any existing text file. The second filename may be new, so the file with this name may not exist.
The program's task is to take the first file of the file, convert it to capital letters, and write another file.
So far I have:
file_old = input("Which file do you want to take ? ")
file_new = input("In which file do you want to put the content? ")
file1 = open(file_old, encoding="UTF-8")
file2 = open(file_new, "w")
for rida in file1:
file2.write(rida.upper())
file1.close()
file2.close()
You have to write the full path to your file for your code to work.
I tested it and it works perfectly.
The input path should be like
C:\Users\yourUserName\PycharmProjects\test_folder\test_small_letters.txt
This should be instead of old.txt that you enter
for example:
"C:\Program Files\Python36\python.exe" C:/Users/userName/PycharmProjects/pythonSnakegame/test_file_capitalize.py
which file you want to take ? C:\Users\userName\PycharmProjects\test_folder\test_small_letters.txt
In which file you want to put the content? C:\Users\userName\PycharmProjects\test_folder\test_big_letters.txt
C:\Users\userName\PycharmProjects\test_folder\test_small_letters.txt
C:\Users\userName\PycharmProjects\test_folder\test_big_letters.txt
Process finished with exit code 0
The new file was created and capitalized.
You can do that in a more pythonic way, with the with statement. This creates a context manager which takes care to close() the file when you are done with it.
file_old = input("Which file do you want to take ? ")
file_new = input("In which file do you want to put the content? ")
with open(file_old, 'r') as f1:
with open(file_new, 'w') as f2:
for line in f1:
f2.write(line)
Related
The purpose is to save the data entered in my program's input in a notepad or file from which Python can gather the information for the next time I run the program.
Example:
name = str(input("Register person: ")) <-- save this value in a file so I can use it even after I close the program, storing it in a list, dictionary or external file using some module/library...
I just want to save some data without overwriting the file everytime i run the program, storing more data like a database, so i can register new "persons" or whatever i want in this file.
You can use open(). Add the file you want to open, and the mode as arguments. 'a' means append, which in your case will be the best to use.
name = str(input("Register person: "))
with open('text.txt', 'a') as file:
file.write(name)
You need to open file in append mode to append data into it
name = str(input("Register person: "))
with open('stored_data.txt', 'a') as f:
f.write(name)
You can use the with open function. So if you want to write something in a file you can do it with:
with open("test.txt","w") as f:
f.write("Your String/Dictionary/Datatype")
if you want to append something, just change the w with the a parameter.
Open the file in 'a' mode and add a end of line.
name = str(input("Register person: "))
with open('text2.txt', 'a') as file:
file.write(f"{name}\n")
All,
I'm trying to read text files that are being downloaded every 20 min in to a certain folder, check it, manipulate it and move it to another location for further processing. Basically, I want to check each file that comes in, check if a string contains a "0.00" value and if so, delete that particular string. There are two strings per file.
I managed to manipulate a file with a given name, but now I need to do the same for files with variable names (there is a timestamp included in the title). One file will need to be processed at a time.
This is what I got so far:
import os
path = r"C:\Users\r1.0"
dir = os.listdir(path)
def remove_line(line, stop):
return any([word in line for word in stop])
stop = ["0.00"]
for file in dir:
if file.lower().endswith('.txt'):
with open(file, "r") as f:
lines = f.readlines()
with open(file, "w") as f:
for line in lines:
if not remove_line(line, stop):
f.write(line)
What works are the def-function and the two "with open..." codes. What am I doing wrong here?
Also, can I write a file to another directory using the open() function?
Thanks in advance!
Your code looks mostly fine. I don't think your list comprehension method does remove the string though. You can write to a different folder with Open(). This should do the trick for you:
import os
path = r"C:\Users\r1.0"
dir = os.listdir(path)
stop = ["0.00"]
for file in dir:
if file.lower().endswith('.txt'):
with open(file, "r") as f:
lines = f.readlines()
# put the new file in a different location
newfile = os path.join("New", "directory", file)
with open(newfile, "w") as f:
for line in lines:
if stop in line: #check if we need to modify lime
#modify line here
#this will remove stop from the line
line.replace(stop, "")
# Regardless of whether the line has changed, we need to write it out.
f.write(line)
Use case:
The user enters an ID code.
A stored file contains information about people, one line per person, including their ID codes.
I need to find this user's line in the file and append that to another text file.
with open("file.txt") as file:
for line in file:
if id_code in line:
yield line
Now what? How do I go from yielding the line to getting it in another file? Also, if the id code isn't in the file at all, can I ask them to try again?
Without the actual txt file, it's hard to say if this will work perfectly, but it's the right general idea.
with open("file.txt", "r") as f, open("otherfile.txt", "a") as g:
for line in file.readlines():
lineparts = line.split()
if id_code in lineparts:
g.write(line)
Basically, I want a script that opens a file, and then goes through the file and sees if the file contains any curse words. If a line in the file contains a curse word, then I want to replace that line with "CENSORED". So far, I think I'm just messing up the code somehow because I'm new to Python:
filename = input("Enter a file name: ")
censor = input("Enter the curse word that you want censored: ")
with open(filename)as fi:
for line in fi:
if censor in line:
fi.write(fi.replace(line, "CENSORED"))
print(fi)
I am new to this, so I'm probably just messing something up...
Line, as in This code (if "Hat" was a curse word):
There Is
A
Hat
Would be:
There Is
A
CENSORED
You cannot write to the same file your are reading, for two reasons:
You opened the file in read-only mode, you cannot write to such a file. You'd have to open the file in read-write mode (using open(filename, mode='r+')) to be able to do what you want.
You are replacing data as you read, with lines that are most likely going to be shorter or longer. You cannot do that in a file. For example, replacing the word cute with censored would create a longer line, and that would overwrite not just the old line but the start of the next line as well.
You need to write out your changed lines to a new file, and at the end of that process replace the old file with the new.
Note that your replace() call is also incorrect; you'd call it on the line:
line = line.replace(censor, 'CENSORED')
The easiest way for you to achieve what you want is to use the fileinput module; it'll let you replace a file in-place, as it'll handle writing to another file and the file swap for you:
import fileinput
filename = input("Enter a file name: ")
censor = input("Enter the curse word that you want censored: ")
for line in fileinput.input(filename, inplace=True):
line = line.replace(censor, 'CENSORED')
print(line, end='')
The print() call is a little magic here; the fileinput module temporarily replaces sys.stdout meaning that print() will write to the replacement file rather than your console. The end='' tells print() not to include a newline; that newline is already part of the original line read from the input file.
Consider:
filename = input("Enter a file name: ")
censor = input("Enter the curse word that you want censored: ")
# Open the file, iterate through the lines and censor them, storing them in lines list
with open(filename) as f:
lines = [line.replace(censor, 'CENSORED').strip() for line in f]
# If you want to re-write the censored file, re-open it, and write the lines
with open(filename, 'w') as f:
f.write('\n'.join(lines))
We're using a list comprehension to censor the lines of the file.
If you want to replace the entire line, and not just the word, replace
lines = [line.replace(censor, 'CENSORED').strip() for line in f]
with
lines = ['CENSORED' if censor in line else line.strip() for line in f]
filename = input("Enter a file name: ")
censor = input("Enter the curse word that you want censored: ")
with open(filename)as fi:
for line in fi:
if censor in line:
print("CENSORED")
else:
print(line)
with open('filename.txt', 'r') as data:
the_lines = data.readlines()
with open('filename.txt', 'w') as data:
for line_content in the_lines:
if curse_word in line_content:
data.write('Censored')
else:
data.write(line_content)
You have only opened the file for reading. Some options:
Read the whole file in, do the replacement, and write it over the original file again.
Read the file line-by-line, process and write the lines to a new file, then delete the old file and rename in the new file.
Use the fileinput module, which does all the work for you.
Here's an example of the last option:
import fileinput,sys
for line in fileinput.input(inplace=1):
line = line.replace('bad','CENSORED')
sys.stdout.write(line)
And use:
test.py file1.txt file2.txt file3.txt
Each file will be edited in place.
This question already has answers here:
Python error message io.UnsupportedOperation: not readable
(5 answers)
Closed 6 months ago.
I am working on a problem that says to make a program that gets a user input for a file and then within the file removes a string that the user specifies. I'm not sure how to go from what I have(below) to what the question asks for. As always any and all help is greatly appreciated.
def main():
outfile = open(input("Enter a file name: "), "a")
string = input("Enter the string to be removed: ")
for string in outfile.readlines():
string = string.replace(string, "")
outfile.close()
print("Done")
main()
I took one of the suggestions and tried to get it to work but as I said in my comment below the code below does not return an error it creates an empty file. What am I missing to get the new file to be the old file with the string removed?
def main():
inpath = input("Enter an input file: ")
line = input("Enter what you want to remove: ")
outpath = input("Enter an output file: ")
with open(inpath, "r") as infile, open(outpath, "w") as outfile:
for line in infile:
outfile.write(line.replace(line, "") + "\n")
print("Done.")
main()
A few side notes before getting into the details: When you call string.replace(string, ""), you're telling the string to replace its entire self with the empty string—you might as well just do string = "". Presumably the first string is the search string to replace, so give it a different name, and then use it as, e.g., string.replace(searchString, ""). Also, you don't want to name a variable string, because it's the name of a standard library module. You're calling your input file "outfile", which is apt to be confusing. You probably want to use a with statement instead of an explicit close. Finally, you can iterate the lines in a file with just for line in f:; you don't need for line in f.readlines() (and, if you ever need to deal with Python 2.x, you'll be much happier avoiding readlines(), because it will read the entire file into memory, and then make a huge list of lines in memory).
The first problem, as JBernardo pointed out, is that you've opened the file in "a" mode, which means "write-only, appending to the end". You can use "a+" or "r+" if you want to read and write.
However, that won't really help you. After all, you can't write to the file in the middle of reading it.
There are a few common ways around this.
First, just write to standard output, and let the user do whatever he wants with the results—e.g., redirect it to a file. (In that case, you have print your prompt, "Done" message, etc. to standard error instead, so they don't get redirected to the file.) This is what many Unix tools like sed or sort do, so it's appropriate if you're building a Unix-style tool, but may not be right for other purposes.
def stderrinput(prompt):
sys.stderr.write(prompt)
sys.stderr.flush()
return input()
def main():
with open(stderrinput("Enter a file name: "), "r") as infile:
searchString = stderrinput("Enter the string to be removed: ")
for line in infile:
print(infile.replace(searchString, ""))
sys.stderr.write("Done\n")
Second, write to another file. Open the input file in "r" mode, and the output file in "w", mode, and then you're just copying lines:
def main():
inpath = input("Enter an input file: ")
outpath = input("Enter an output file: ")
with open(inpath, "r") as infile, open("outpath", "w") as outfile:
for line in infile:
outfile.write(line.replace(searchString, "") + "\n")
Third, read and process the whole file in memory, then truncate and rewrite the whole file:
def main():
path = input("Enter an input/output file: ")
with open(path, "r+") as inoutfile:
lines = [line.replace(searchString, "") for line in inoutfile]
inoutfile.seek(0)
inoutfile.truncate()
inoutfile.writelines(lines)
Finally, write to a temporary file (as with the second option), then move that temporary file on top of the original input file. Something like this:
def main():
path = input("Enter an input/output file: ")
with open(path, "r") as infile, tempfile.NamedTemporaryFile("w", delete=False) as outfile:
for line in infile:
outfile.write(line.replace(searchString, ""))
shutil.move(outfile.name, pathname)
This last one is a little tricky, because of the differences between POSIX and Windows. However, it has some big advantages. (For example, if your program gets killed in the middle of operation, no matter how it happens, you're guaranteed to have either the original file or the new file, not some half-written mess.)