how to rename a file and keep the original - python

I would like to keep unaltered the template.txt file after I insert some text into it and save the altered text file with a new name. Currently, my code overwrites the template.txt.
f = open("template.txt", "r")
contents = f.readlines()
f.close()
#insert the new text at line = 2
contents.insert(2, "This is a custom inserted line \n")
#open the file again and write the contents
f = open("template.txt", "w")
contents = "".join(contents)
f.write(contents)
f.close()
os.rename('template.txt', 'new_file.txt')

As people have mentioned, you're going to want to copy the contents of template.txt into a new file and then edit this new file. This allows you to keep the original file unmodified and you don't have to worry about renaming files at the end. Another tip: the with open(file) as f syntax keeps you from having to remember to close files when you're editing them and is the recommended way of working with files in python
with open("template.txt") as f:
lines = f.readlines()
with open("new_file.txt", "w+") as n:
lines.insert(2, "This is a custom inserted line \n")
n.writelines(lines)

Related

printing the content of a file, but getting an int as an output (number of characters in the file) in Python

I wrote a function that copies the content of one file to a new file.
the function gets 2 parameters:
the directory of the copied file
the directory of the new file.
When I try to print the content of the copied file, I get the content of the file (which is what I want), But when I try to do the same thing with the new file, I get the number of characters inside the file (14 in this case).
I don't understand why do I get 2 different outputs with the same (at list as per my understanding) lines of code.
Would be happy to get some help, thank you!
Here's my code:
# creating the file that's going to be copied:
with open(source_link, 'w') as f:
f.write('Copy this file')
# the function:
def copy_file_content(source, destination):
# getting the content of the copied file:
f1 = open(source, 'r')
copied_file = f1.read()
f1.close()
# putting the content of the copied file in the new file:
f2 = open(destination, 'w')
new_file = f2.write(copied_file)
f2.close
# print old file:
print(copied_file)
print('***')
# print new file:
print(new_file)
copy_file_content(source = source_link, destination = dest_link)
Output:
Copy this file
***
14
As referenced in Python documentation:
f.write(string) writes the contents of string to the file, returning the number of characters written.
Opposed to f.read(), which returns file contents.
If you want to read contents of copied_file, you will need to open it again in read mode:
with open(destination, 'r') as f:
new_file = f.read(copied_file)
.read() returns the file contents, which is why when copied_file is set to f1.read(), you can print the contents out. However, .write() performs the write operation on the file and then returns the number of characters written.
Therefore new_file contains the number of characters written. Rather than setting the value of new_file to f2.write(), you must open the new file again in read mode, and then perform file.read()
def copy_file_content(source, destination):
# getting the content of the copied file:
with open(source, 'r') as f1:
copied_file = f1.read()
# putting the content of the copied file in the new file:
with open(destination, 'w') as f2:
f2.write(copied_file)
with open(destination, "r") as f2_read:
new_file = f2_read.read()
# print old file:
print(copied_file)
print('***')
# print new file:
print(new_file)
copy_file_content(source = source_link, destination = dest_link)

reading file only once throughout the other functions

with open('sample.txt', 'r') as f:
def function1():
file = f.readlines()
...code that will read the file and modify
def function2():
file = f.readlines()
...code that will read the file and modify
with open('output.txt', 'w') as outputFile:
for file in file:
function1()
function2()
Here is my code. I am trying to read the file only once. I have functions that will read different parts from the file and write it as in output.txt file.
I tried but it is giving me an error "ValueError: I/O operation on closed file."
helpp
If you're reading all of the file in each function, you're better off doing something like the following:
with open('sample.txt','r') as f:
file = f.readlines()
function1(file) # so don't readline multiple times
function2(file) # in your function just operate on data
with open('output.txt', 'w') as f:
f.writelines(file)
Firstly, some notes:
The for file in file piece means "For each line in the file I will do the following".
Your 2 functions are not indented (I think) so that could cause an issue also.
f.readlines() takes the whole file and stores it as the variable named file.
The best approach to this would be to read the file 1 time with file = f.readlines(). Now that file has all the lines, loop over those lines while making any changes that you need to make. For each line, save that line to a new file (look up how append works).
Right now you aren't printing anything out which makes debugging very hard when you are new, so start with this:
def my_change_text_function(line):
#here you can write code that will have the 1 line available to change.
changed_line = ......
return changed_line
f = open("pok.txt")
newfile = open("newfile.txt", "a")
file = f.readlines()
for line in file:
print(line)
changed_line = my_change_text_function(line)
#Do your changes to the line here, character replacement, etc.
newfile.write(changed_line)
Now you will have a new file named newfile.txt that contains your changes. This is all of the code required, minus the code you need to modify the line.

How to create a new file and copy content of existing file into newly created file python

I have a python function here that takes in 2 params, old_file is the name of the file that contains the content that I want to copy over to the new file and the new_file is the name for the file I want to create. Right now my code looks like this and it would throw an error which is a type error that says "TypeError: expected str, bytes or os.PathLike object, not TextIOWrapper". Is there a more efficient way to do it?. In addition when I point at with open(file, "r+") as f2: I get this warning
Note. this works if the file is already pre-made but not when i make it in the function
def copy_In(old_file, new_file):
file = open(new_file, "w")
with open(file, "r+") as f2:
for x in range(10):
f2.readline()
pos = f2.tell()
f2_remainder = f2.read()
f2.seek(pos)
with open(old_file, "r") as f1:
for line in f1:
f2.write(line)
f2.write(f2_remainder)
just do it like:
def copy_file(old_fname, new_fname):
with open(old_fname, "rt") as old_fobj, open(new_fname, "wt") as new_fobj:
new_fobj.write(old_fobj.read())
we are opening first file in read mode and second in write mode and reading the entire content of first file and writing it in second file.

os.path.join does not yield the contents of the file

print "Which category would you like to view? Savory, Dessert, Cake, Soup or Drink? "
category = raw_input()
for x in os.listdir(category): print x
name = raw_input("Which recipe would wou like to view? ")
fullname = os.path.join(category, name)
f = open(fullname, "r");
print f
I am writing a program that will allow users to view the contents of .txt files saved in specific directories. When I run this code I don't get the contents and instead get a message that says this:
open file 'savory/b.txt', mode 'r' at 0x1004bd140
any ideas. I am new to python so i dont have much of an idea as to what is causing the error but i assume it is due to some missing code.
Thank you.
The return value of open is a file object (not the file contents!) .You need to call a method on your file object to actually read the file:
f = open(fullname, "r")
print f.read()
f.close()
If it's a big file you may want to iterate over the file line-by-line
f = open(fullname, "r")
for line in f:
print line
f.close()
On a side note, here's alternate syntax to you don't have to remember to call the close method:
with open(fullname, "r") as f:
for line in f:
print line

Python- need to append characters to the beginning and end of each line in text file

I should preface that I am a complete Python Newbie.
Im trying to create a script that will loop through a directory and its subdirectories looking for text files. When it encounters a text file it will parse the file and convert it to NITF XML and upload to an FTP directory.
At this point I am still working on reading the text file into variables so that they can be inserted into the XML document in the right places. An example to the text file is as follows.
Headline
Subhead
By A person
Paragraph text.
And here is the code I have so far:
with open("path/to/textFile.txt") as f:
#content = f.readlines()
head,sub,auth = [f.readline().strip() for i in range(3)]
data=f.read()
pth = os.getcwd()
print head,sub,auth,data,pth
My question is: how do I iterate through the body of the text file(data) and wrap each line in HTML P tags? For example;
<P>line of text in file </P> <P>Next line in text file</p>.
Something like
output_format = '<p>{}</p>\n'.format
with open('input') as fin, open('output', 'w') as fout:
fout.writelines( output_format(line.strip()) for line in fin )
This assumes that you want to write the new content back to the original file:
with open('path/to/textFile.txt') as f:
content = f.readlines()
with open('path/to/textFile.txt', 'w') as f:
for line in content:
f.write('<p>' + line.strip() + '</p>\n')
with open('infile') as fin, open('outfile',w) as fout:
for line in fin:
fout.write('<P>{0}</P>\n'.format(line[:-1]) #slice off the newline. Same as `line.rstrip('\n')`.
#Only do this once you're sure the script works :)
shutil.move('outfile','infile') #Need to replace the input file with the output file
in you case, you should probably replace
data=f.read()
with:
data = '\n'.join("<p>%s</p>" % l.strip() for l in f)
use data=f.readlines() here,
and then iterate over data and try something like this:
for line in data:
line="<p>"+line.strip()+"</p>"
#write line+'\n' to a file or do something else
append the and <\p> for each line
ex:
data_new=[]
data=f.readlines()
for lines in data:
data_new.append("<p>%s</p>\n" % data.strip().strip("\n"))
You could use the fileinput module to modify one or more files in-place, with optional backup file creation if desired (see its documentation for details). Here's it being used to process one file.
import fileinput
for line in fileinput.input('testinput.txt', inplace=1):
print '<P>'+line[:-1]+'<\P>'
The 'testinput.txt' argument could also be a sequence of two or more file names instead of just a single one, which could be useful especially if you're using os.walk() to generate the list of files in the directory and its subdirectories to process (as you probably should be doing).

Categories

Resources