Need help for making this .txt files TRUE - python

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)

Related

Taking user input to create text file names with prewritten name and user input

Hi I'm trying to create a couple text files with a prewritten tag along with a given user input.
For Ex. I need 5 file names with a prewritten tag and the input
Cat100.txt
Where cat is predetermined and the number 100 is the user input.
I have this but I can't find out how to add a prewritten tag along with the user input.
filename = input ("filename: ");
with open (filename, "w") as f:
Thank you!
Updated per comment clarifications:
import os
folderpath = ".\\test_folder\\"
prewritten_tag = "User wrote: " # example
user_filename = input("filename: ")
full_filename = prewritten_tag + user_filename
fullpath = os.join(folderpath,full_filename) # gets absolute path
with open(fullpath, "w") as f:
user_input = input()
full_txt = stuff + input() + otherstuff
f.write(full_txt)

Replace Variables in a .docx file with user inputted variables

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')

Writing functions to allow user define file name and enter file contents

I am learning Python as a beginner and have a question that I couldn't figure out. I need to write functions to allow users to setup/give a file a name and then enter contents.
The error message I got is: "Str' object is not callable. I don't know how to fix this. Please could you help me out. Many thanks!
The code is as follows:
=========================================
WRITE = "w"
APPEND = "a"
fName = ""
def fileName(): #to define name of the file.
fName = input("Please enter a name for your file: ")
fileName = open(fName, WRITE)
return fileName
#now to define a function for data entry
dataEntry = ""
def enterData():
dataEntry = input("Please enter guest name and age, separated by a coma: ")
dataFile = open(fName, APPEND(dataEntry))
fName.append(dataEntry)
return dataFile
#to determine if it's the end of data entry
moreEntry = input("Anymore guest: Y/N ")
while moreEntry != "N":
enterData() #here to call function to repeat data entry
fName.close()
fileName()
enterData()
print("Your file has been completed!")
fileContents = fName.readline()
print(fileContents)
I ran the code and... I seeing the error as line 14
14 dataFile = open(fName, APPEND(dataEntry))
APPEND appears to be a str. It does not appear to be a function.
fName is not declared in this scope. Your function spacing is off. Maybe you meant to run the all the code in order rather than in parts?
As it is, fName is declared and defined once globally (line 4), declared and defined in function filename() (line 6).
fName is also referred to in the function (line 7) Called unsuccessfully in line 14
dataFile = open(fName, APPEND(dataEntry)) # fName has not been declared in function enterData()
I suspect your code would work if you reordered your lines and not use functions (due to references) Also, please close your files. EG
f = open ("somefile.txt", "a+")
...
f.close() #all in the same block.
Thanks for all the inputs. Much appreciated. I've reworked the code a bit, and to put all data entry into a list first, then try to append the list to the file. It works, to a certain extent (about 80%, perhaps!)
However, I now have another problem. When I tried to open the file to append the list, it says "No such file or directory" next to the code (line31): "myFile = open(fName, APPEND)". But I thought I declared and then let user define the name at the beginning? How should I make it work, please?
Thanks in advance again!
WRITE = "w"
APPEND = "a"
fName = ""
def fileName(): #to define name of the file.
fName = input("Please enter a name for your file: ")
fileName = open(fName, WRITE)
fileName.close()
return fileName
#now to define a function for data entry
dataEntry = ""
dataList = []
def enterData():
dataEntry = input("Please enter guest name and age, separated by a coma: ")
dataList.append(dataEntry)
return
fileName()
enterData()
#to determine if it's the end of data entry
moreEntry = input("Anymore guest: Y/N ")
if moreEntry == "Y":
enterData()
else:
print("Your file has been completed successfully!")
myFile = open(fName, APPEND)
myFile.append(dataList)
myFile.close()
fileContents = fName.readline()
print(fileContents)

I/O Error with open()

class NewTab():
def __init__(self, song_title, artist_name):
self.song_title = song_title
self.artist_name = artist_name
name1 = self.artist_name + "_" + self.song_title
name2 = name1.replace(" ", "")
new_file = open("~/Documents/"+name2+".txt", "a+")
tab = NewTab(raw_input("Song Title: "), raw_input("Artist Name: "))
I am trying to create a new file (assuming it doesn't already exist) whose name is generated from two strings of User input. For example:
"Song Title: " >> Personal Jesus
"Artist Name: " >> Depeche Mode
should result in creating: ~/Documents/DepecheMode_PersonalJesus.txt
Unfortunately I am always left with:
IOError: [Errno 2] No such file or director: '~/Documents/DepecheMode_PersonalJesus.txt'
I have tried different open() modes, such as "w", "w+" and "r+" to no avail.
I have also tried placing name1, name2, and new_file into a method outside of __init__ like so:
def create_new(self):
name1 = self.artist_name + "_" + self.song_title
name2 = name1.replace(" ", "")
new_file = open("~/Documents/"+name2+".txt", "a+")
tab.create_new()
but this results in the exact same Error.
I have set my /Documents folder Permissions (Owner, Group, Others) to Create and delete files.
Beyond that, I am at a complete loss as to why I cannot create this file. It is clearly structuring the file name and directory the way that I want it, so why won't it go ahead and create the file?
Use os.path.expanduser() function to get a full valid path with "~" resolved and pass this to open()
new_file = open(os.path.expanduser("~/Documents/")+name2+".txt", "a+")
this will resolve "~" to something like /home/user and join it with the rest of the path elements.
If you don't necessarily need to use "a+" then having "wb" as a second parameter will automatically open a file.
foo = open("bar", "wb")

Why can't I override the default argument?

Consider the following code:
import pickle
def open_file(fname, fname1 = None):
# returns a new OPEN file
if fname1:
while fname == fname1:
f_name = input("File already open, filename: ")
f = None
while not f:
try:
f = open(fname, "rb")
except IOError:
fname = input("File not found, filename: ")
print(fname, "open")
return f
def get_2cubes():
a_name = input("\nWhat is the name of the first cube's file? ")
a_file = open_file(a_name)
#a_cube = pickle.load(a_file)
a_file.close()
b_name = input("\nWhat is the name of the second cube's file? ")
b_file = open_file(b_name, a_name)
#b_cube = pickle.load(b_file)
b_file.close()
#return a_cube, b_cube
get_2cubes()
The code is meant to open a second file only if it's not the first file.
The first file's name is represented by fname1 in open_file(). If the name of the second file (b_name in this case) matches that of the first file the user will be prompted to enter a new name.
I supplied a default argument of None for the fname1 parameter because the function will sometimes be used only for opening one file and not for also comparing it to another file. However, I can't seem to override the default argument.
The a_name variable from the 7th line of get_2cubes is not being recognized by the if fname1: condition in open_file, and as a result I can open the same file twice. How would I correct this?
I think you need to use raw_input. Otherwise the text entered will treated as a variable name, and therefore will equal to None. (Unless you're on Python 3)

Categories