Replace Variables in a .docx file with user inputted variables - python

I have a project that I am working on. I have a .docx template that I've created.
Within there, I have multiple variables across the whole document that need to be replaced with user-imputed information, (some variables are replaces more than once within the doc).
I have this code that I modified from previous .txt files that I have worked with. I am not able to take the .docx file, edit the vars with user imputed info and create a new file that I can share/print. Any help would be appreciated.
I have attempted to try to use python-docx but alas, I have not fully understood the concept and make it work.
Sample code follows:
from __future__ import with_statement
import fileinput
#def terms and ask user for imput
def loaDocOne():
words = ["[clientName]","[addressLine1]","[addressLine2]","[todaysDate]","[fileNum]","[originalClient]","[refNum]","[currentBal]","]
clientName = input('Enter Clients name: ')
addressLine1 = input('Enter Clients Address Line 1: ')
addressLine2 = input('Enter Clients Address Line 2: ')
todaysDate = input('Enter Todays Date: ')
fileNum = input('Enter File Number: ')
originalClient = input('Enter Original Client: ')
refNum = input('Enter Original Refrence Number: ')
#open file
def replaceFunc():
with open ('template.docx') as f:
for line in f:
line = line.replace("[clientName]",clientName)
line = line.replace("[addressLine1]",addressLine1 )
line = line.replace("[addressLine2]",addressLine2 )
line = line.replace("[todaysDate]",todaysDate)
line = line.replace("[fileNum]",fileNum )
line = line.replace("[originalClient]", originalClient)
line = line.replace("[refNum]",refNum )
#Find out if everything looks good to continue
def goOn():
doYouWantToContinue = input('Does Everything Look Correct? yes/no: ')
if doYouWantToContinue == 'yes':
replaceFunc()
else:
loaDocOne()
loaDocOne()
goOn()
replaceFunc()
Also, Is there a way to take the outputted file and make it 'document_name_'fileNum'' with the user provided file number?

Using the python-docx module is the easiest way to proceed. The structure of a document opened using this module is documented here, and I think it's pretty easy to wrap your head around.
This code opens a document, then for each of it's paragraphs it replaces the existing text with the replaced text, using the str.replace function that automatically replaces all occurrences of some string.
from docx import Document
doc = Document('document.docx')
replacements = {
'%replace_me_1%': 'New text 1',
'%replace_me_2%': 'New text 2'
}
for paragraph in doc.paragraphs:
for key in replacements:
paragraph.text = paragraph.text.replace(key, replacements[key])
doc.save('document.docx')
Saving the file with a new name should be quite easy:
file_suffix = input()
doc.save('document_' + file_suffix + '.docx')

Related

Deleting a line in a txt file that contains a certain string [duplicate]

This question already has answers here:
Using Python to Remove All Lines Matching Regex
(3 answers)
Closed 3 months ago.
I want to search a text file for the user input and delete the line that contains it.Below is the text file.
course work.txt:-
Eric/20/SL/merc/3433
John/30/AU/BMW/2324
Tony/24/US/ford/4532
Leo/32/JP/Toyota/1344
If the user input is 'Eric', I want the line containing 'Eric' to be deleted and then the text file to be saved as below
Updated course work.txt:-
John/30/AU/BMW/2324
Tony/24/US/ford/4532
Leo/32/JP/Toyota/1344
Here is the code I created for that with the help of the very very small knowledge I have and some websites.
with open('course work.txt','r') as original:
#get user input
word = input('Search: ')
# read all content of file
content = original.read()
# check if string present in file
if word in content:
print('User input exsists')
confirmation = input('Press enter to delete')
if confirmation == '':
import os
with open('course work.txt', 'r') as original:
with open('temp.txt', "w") as temporary:
for line in original:
# if user input contain in a line then don't write it
if word not in line.strip("\n"):
temporary.write(line)
os.replace('temp.txt', 'course work.txt')
else:
print('Driver doesn't exsist')
What's happening here is,
1.open the course work.txt and read it
2.get the user input and search course work.txt for that user input
3.if that user input is found in the course work.txt, open a new file called temp.txt
write the all lines except the line that contains the user input into temp.txt
5.over write temp.txt on course work.txt
When I run the code it gives me a 'PermissionError: [WinError 5] ' error.The temp.txt file get created. It contains all the lines except the line i want to delete which is great, but it doesn't over write on the original file. Is there way to solve this or is there a more PYTHONIC way to do the exact same thing?
You can write a function to take care of that and also by making good use of shutil to copy temp.txt after writing in order to update source-work.txt .
import shutil
def modify_original_file():
word = input('Search: ').strip().lower()
track = 0
with open("course-work.txt", 'r') as original:
with open("temp.txt", "w") as temporary:
# read all lines of file
content = original.readlines()
# check if string present in file
word_found = False
for line in content:
if word in line.lower():
word_found = True
break
if word_found == True:
print('User input exist')
confirmation = input('Press Enter to delete: ')
if confirmation == '':
for line in content:
if word not in line.lower():
temporary.write(line)
track += 1
else:
print("Driver doesn't exist")
if track > 0:
# Update course-work.txt by copying temp.txt file
shutil.copyfile("temp.txt", "course-work.txt")
modify_original_file()
Terminal: Enter Eric or eric for search.
Search: eric
Output: updated source-work.txt:
John/30/AU/BMW/2324
Tony/24/US/ford/4532
Leo/32/JP/Toyota/1344

Need help for making this .txt files TRUE

Good day everyone, How can i make this thing make TRUE? I already have existed .txt files but the outcome always False.
ID = input("Enter the name of your .txt file: ") +".txt" +"'"
IDS = "'" + ID
file_exists = os.path.exists(IDS)
print(file_exists)
print(IDS)
Get rid of ' before and after the file name:
ID = input("Enter the name of your .txt file: ") +".txt"
file_exists = os.path.exists(ID)
print(file_exists)
print(ID)
For example, if you had foo.txt and you put foo into your program, then your current code would look for a file named 'foo.txt', not foo.txt.
Try this:
#You may want to use str.strip() to get rid of unnecessary whitespaces
ID = input("Enter the name of your .txt file: ").strip() + ".txt"
file_exists = os.path.exists(ID)
print(f'{ID} exists') if file_exists else print(f'{ID} file does not exist')
Remove the quotes, you are adding single quotes to start and end of your string. Your code should look like this:
ID = input("Enter the name of your .txt file: ") +".txt"
file_exists = os.path.exists(ID)
print(file_exists)
print(IDS)
Quotes in programming languages indicate what are strings, and they are omitted by the interpreter when you output it into a terminal (print)

Trying to create a program in Python that changes names from said .txt file into usernames

So basically I am making a program that writes the .txt file and changes the names in form by last to first like Woods, Tiger and turn them into usernames in this form twoods. They have to be formatted all in lower case and I think I messed up my code somewhere. Thanks!
The code I tried, below:
def main():
user_input = input("Please enter the file name: ")
user_file = open(user_input, 'r')
line = user_file.readlines()
line.split()
while line != '':
line = user_file.readline()
print(line.split()[-1][0][0:6]+line.split()[0][0:6]).lower() , end = '')
user_file.close()
if __name__ == "__main__":
main()
try this:
line = "Tiger Woods"
(fname, lname) = line.split(" ")
print(f'{fname[0:1]}{lname}'.lower())
There appear to be a couple of little issues preventing this from working / things that can be improved,
You are trying to split a list which is not possible. This is a string operation.
You are manually closing the file, this is not ideal
The program will not run as you are not using __name__ == "__main__"
Amended code,
def main():
user_input = input("Please enter the file name: ")
with open(user_input, 'r') as file_handler:
for line in file_handler:
print((line.split()[-1][0][0:6] + line.split()[0][0:6]).lower(), end='')
if __name__ == "__main__":
main()
If i understand your problem correctly, you want to read Surname,Name from a file line by line and turn them into nsurname formatted usernames.
For that, we can open and read the file to get user informations and split them line by line and strip the \n at the end.
After that, we can loop the lines that we read and create the usernames with given format and append them to an array of usernames.
Code:
# Get filename to read.
user_input = input("Please enter the file name: ")
# Open the given file and readlines.
# Split to lines and strip the \n at the end.
user_names = []
with open(user_input,'r') as user_file:
user_names = user_file.readlines()
user_names = [line.rstrip() for line in user_names]
print("User names from file: " + str(user_names))
# Loop the user informations that we read and split from file.
# Create formatted usernames and append to usernames list.
usernames = []
for line in user_names:
info = line.split(',')
username = (info[1][0:1] + info[0]).lower()
usernames.append(username)
print("Usernames after formatted: " + str(usernames))
Input File(test.txt):
Woods,Tiger
World,Hello
Output:
Please enter the file name: test.txt
User names from file: ['Woods,Tiger', 'World,Hello']
Usernames after formatted: ['twoods', 'hworld']

CSV rewriter keeps creating new headers

My code is creating the same headers each time, I want it to create one and append the data to a CSV without creating a new header.
What it looks like in the CSV
What I want it to look like
import csv
with open("Details.csv","a+") as Details:
w=csv.writer(Details,delimiter=",")
headers1=["Name","Age","Year Group"]
line=Details.readlines()
if line!=["Name","Age","Year Group"]:
w.writerow(headers1)
print("Welcome User, to my Topics Quiz!\n-------------------------------
--------\nYou can choose from 3 different topics:\n • History\n •
Music\n • Computer Science\n---------------------------------------")
print("Before we start, we need to register an account.")
User=input("Enter your name:\n")
Age=input("Enter your age:\n")
Year=input("Enter your year group:\n")
details=[User,Age,Year]
w.writerow(details)
Details.close()
with open("UserPass.csv","a+") as Userpass:
w=csv.writer(Userpass,delimiter=",")
headers2=["Username","Password"]
if headers2 not in Userpass:
w.writerow(headers2)
NewUser=(User[:3]+Age)
print("Great! Your username is set to: {}".format(NewUser))
Pass=input("Enter a password for your account:\n")
userpass=[NewUser,Pass]
w.writerow(userpass)
Userpass.close()
Any help is greatly appreciated.
You are opening file in appending mode (https://docs.python.org/3/library/functions.html#open), so this line=Details.readlines() will always be empty line and your headers will be written every time (code will always get into if).
It is similar with other file. So I suggest you first check if file exist, and if not create it and add headers, and remove headers part from with:
import csv
import os.path
if not os.path.isfile("Details.csv"):
with open("Details.csv", "a+") as Details:
w = csv.writer(Details, delimiter=",")
headers1 = ["Name", "Age", "Year Group"]
w.writerow(headers1)
Details.close()
if not os.path.isfile("UserPass.csv"):
with open("UserPass.csv", "a+") as Userpass:
w = csv.writer(Userpass, delimiter=",")
headers2 = ["Username", "Password"]
w.writerow(headers2)
Userpass.close()
with open("Details.csv", "a+") as Details:
w = csv.writer(Details, delimiter=",")
print("Welcome User, to my Topics Quiz!\n-------------------------------"
"--------\nYou can choose from 3 different topics:\n • History\n • "
"Music\n • Computer Science\n---------------------------------------")
print("Before we start, we need to register an account.")
User = input("Enter your name:\n")
Age = input("Enter your age:\n")
Year = input("Enter your year group:\n")
details = [User, Age, Year]
w.writerow(details)
Details.close()
with open("UserPass.csv", "a+") as Userpass:
w = csv.writer(Userpass, delimiter=",")
NewUser = (User[:3] + Age)
print("Great! Your username is set to: {}".format(NewUser))
Pass = input("Enter a password for your account:\n")
userpass = [NewUser, Pass]
w.writerow(userpass)
Userpass.close()
There are different problems in your code:
1) Empty line between lines with data in csv file, it happens because of the nonbinary type of opening and can be fixed by adding that arg in open function:
w=csv.writer(Details,delimiter=",",lineterminator='\n')
2) In your case Details.readlines() method was returning [], because of the a+ type of opening, it's supposed to add lines in the end of file, so pointer is in the end already and we need to return it at the beginning by using that code:
line=Details.seek(0)
3) Also, we need only first line, so just use readline() method. And after all, your condition should look that way, because of the return type and the fact that there's \n in the end of every line:
if line!="Name,Age,Year Group\n":
And the full code of that part. Let me know if it works well for you:
w=csv.writer(Details,delimiter=",",lineterminator='\n')
headers1=["Name","Age","Year Group"]
line=Details.seek(0)
line=Details.readlines()[0]
print(line)
if line!="Name,Age,Year Group\n":
w.writerow(headers1)
I don't understand everything your code is trying to accomplish, but the following will add a row to the Details.csv without creating any new headers:
import csv
import os
csv_fileheader = "Name", "Age", "Year Group"
csv_filename = "Details.csv"
print("Welcome User, to my Topics Quiz!\n"
"---------------------------------------\n"
"You can choose from 3 different topics:\n"
" • History\n • Music\n • Computer Science\n"
"---------------------------------------")
print("Before we start, we need to register an account.")
user = input("Enter your name:\n")
age = input("Enter your age:\n")
year = input("Enter your year group:\n")
if not os.path.isfile(csv_filename): # Create file if it doesn't exist.
with open(csv_filename, "w", newline='') as csv_file:
csv.writer(csv_file).writerow(csv_fileheader) # Put header row in it.
with open(csv_filename, "a+", newline='') as details2:
writer = csv.writer(details2, delimiter=",")
writer.writerow((user, age, year))
You should consider following the PEP 8 - Style Guide for Python Code recommendations as it will make your code easier for both you and others to read.

How would I tell Python to write to a new line if the previous line is occupied with other text?

Let's suppose I had text on line one of a text file created via to a Python script. I exit out of the script and then access it a few days later. I go to add another entry of information but it overwrites line one. How would I tell Python to check line x before adding to it? My code is below, you don't need to add to my code you can just give me a quick and simple example. Thanks,
Noah Rainey
def start():
command = raw_input('''
1) Add
2) Look Up
3) See All
4) Delete Entry
''')
if command=="1":
add()
if command=="2":
look_up()
def add():
name = raw_input("What is your name?")
age = str(raw_input("How old are you?"))
favcolor = raw_input("What is your favorite color?")
fileObj = open("employees.txt","w")
fileObj.write("Name:"+name+" ")
fileObj.write("Age:"+age+" ")
s = line.split()
n = len(s)
fileObj.write('''
''')
fileObj.close()
print "The following text has been saved:"
print "Name:"+name
print "Age:"+age
print "Favorite Color"+favcolor
start()
def look_up():
fileObj = open("employees.txt","r")
line = raw_input("What line would you like to look up:")
line = fileObj.readline()
print line
You need to open the file in "append" mode, like this:
with open("filename", "a") as f:
f.write("Next line\n")
Using the mode "w" in the open()call will overwrite your file.

Categories