Python script error- Save output to a text file - python

I am trying to save the output to a file and the indentations are ok.. but I keep getting this error please see below:
This is the error below:
Traceback (most recent call last):
File "command.py", line 36, in <module>
file.write(output)
TypeError: expected a character buffer object
Can someone look at my code below and see what I am doing wrong. I am new to python so any help would be appreciated.
#Importing the necessary module. help
from trigger.cmds import Commando
#Asking the user for input.
devices = raw_input('\nEnter devices separated by comma: ')
commands = raw_input('\nEnter commands separated by comma: ')
#Splitting the devices/commands entered by the user.
devices_list = devices.split(',')
commands_list = commands.split(',')
#Running all given commands on all given devices.
cmd = Commando(devices = devices_list, commands = commands_list)
#Executing all the work.
cmd.run()
#Capturing the results
output = cmd.results
#print output
#Asking the user if they want to print to screen or save to file.
user_option = raw_input('Type "p" to print to screen or "s" to save to file: ')
if user_option == 'p':
print output
elif user_option == "s":
filename = raw_input('Please name your file. Example: /home/ubuntu/bgp.txt: ')
#Print the output to file.
with open(filename, 'w') as file:
file.write(output)
print "Done...Check out %s to see the results." % filename
#End of Program
Please help with this code

Convert output variable to string object using str method
EX:
with open(filename, 'w') as file:
file.write(str(output))

Related

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

Can Someone tell me how to put a .text file in to a dictionary containing a number and a string with python

I am making a project about a contact saver but I am not able to read a single contact in the code...
Please help me...
I am giving the code and the problem
If you can please provide me with the whole part of finding the single user or all the related users...
Thanks...
what = input("Do you want to read a single contact(y, n): ")
if what == 'y':
who = input("Please Enter the name: ")
a = open('contacts.txt', 'a')
for line in a:
k, v = line.strip().split('=')
users[k.strip()] = v.strip()
a.close()
for i in users:
if who.lower() == i.lower() or i.startswith(who[:3]):
print(i)
and this is the error:
'
Traceback (most recent call last):
File "C:/Users/Teerth Jain/Desktop/teerth_made_projects/contacts.py", line 18, in
for line in a:
io.UnsupportedOperation: not readable enter code here
'
You've opened the file in a writing mode as opposed to a reading mode, use "r" instead of "a" (which is append to file)
a = open('contacts.txt', 'r')
Also, not sure if you've included your question's indentation correctly, but the a.close() should be outside the for loop
As noted in the comments, using with is preferred over explicitly closing the file.
with open('contacts.txt', "r") as a:
for line in a:
k, v = line.strip().split('=')
users[k.strip()] = v.strip()

I am prompted with an error message when I run it

I have this program working how it should be but there is 1 small problem that I'm having and I really don't know what to do about it. I feel like to fix the problem I have to reformat my entire program. In the very beginning of the while loop. I created a with statement that executes what the program is supposed to do. The program opens a file, reads it, and outputs how many unique words there are in a text file. The with statement works, but now the error checking past the with statement does not execute and I'm prompted with an error. When you input a file that does not exist it is supposed to prompt the user saying "The file (filename) does not exist!" But that code past the with statement is no longer executed and I'm prompted with a FileNotFoundError.
def FileCheck(fn):
try:
open(fn, "r")
return 1
except IOError:
print("The file " + filename + " was not found!")
return 0
loop = 'y'
while loop == 'y':
filename = input("Enter the name of the file you wish to process?: ")
with open(filename, "r") as file:
lines = file.read().splitlines()
uniques = set()
for line in lines:
uniques = set(line.split())
print("There are " + str(len(uniques)) + " unique words in " + filename + ".")
if FileCheck(filename) == 1:
loop = 'n'
else:
exit_or_continue = input("Enter the name of the file you wish to process or type exit to quit: ")
if exit_or_continue == 'exit':
print("Thanks for using the program!")
loop = 'n'
else:
break
Here is the error message when I input a file that does not exist
Enter the name of the file you wish to process?: aonsd.txt
Traceback (most recent call last):
File "C:/Users/C/PycharmProjects", line 21, in <module>
with open(filename, "r") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'aonsd.txt'
Your problem is a logic problem here:
filename = input("Enter the name of the file you wish to process?: ")
with open(filename, "r") as file:
...
if FileCheck(filename) == 1:
You very clearly input a file name and then, without bothering to check its existence, try to open it. You don't check until you've finished reading the file.
The logic you expressed in your written description suggests that you want
filename = input("Enter the name of the file you wish to process?: ")
if FileCheck(filename):
with open(filename, "r") as file:
...

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)

Can't Take in Multiple Text File

Hello this is a problem I am having. The following program doesn't allow me to take in multiple outplane data but it allow to take in multiple in plane data according to the function in call_Controller. Is there something wrong with the program?
you can try by creating this 4 text file in a folder.
run the program and press Clt to take in both hello.txt and bye.txt
follow by hello1.txt and bye1.txt and you will know the error
somebody please help me with this problem..
hello.txt | hello1.txt
bye.txt | bye1.txt
Error Message:
Traceback (most recent call last):
File "C:\ProjectMAPG\TRYPYTHON\src\OldPythonTry.py", line 100, in <module>
Name = call_Controller(file_path_IP, InputfilesListOoplane)
File "C:\ProjectMAPG\TRYPYTHON\src\OldPythonTry.py", line 67, in call_Controller
with open(InputfilesListOoplane) as f1:
IOError: [Errno 22] invalid mode ('r') or filename: u'C:/Users/zhenhui/Desktop/bye1.txt C:/Users/zhenhui/Desktop/hello1.txt'
function to extract the file name:
def extractFilename(FileNameOnly):
stripText = string.split(FileNameOnly, " ")
FileName = stripText[0]
return (FileName)
pass
I think the problem is here. As the outplane have doesn't allow me to take in multiple folder:
def call_Controller(file_path_Inplane, InputfilesListOoplane):
FileNameOnlyIP = splitext(basename(file_path_Inplane))[0]
Name = extractFilename(FileNameOnlyIP)
#Extract raw inplane
with open(file_path_Inplane) as f:
f.readline()
#Extract raw outplane
with open(InputfilesListOoplane) as f1:
f1.readline()
return Name
Start of the program:
if __name__ == '__main__': #start of program
win = Tk.Tk() #Open up connection and declare button and label
master=win
initial_dir = "C:\VSM"
#Create Directory if its not there
try:
if not os.path.exists(newDirRH[0]):os.makedirs(newDirRH)
except: pass
#Open to select multiple files for files
file_path_Inplane= tkFileDialog.askopenfilename(initialdir=initial_dir, title="Select VSM Files", multiple =1)
if file_path_Inplane != "": pass
else:
print "You didn't open anything!"
InputfilesListInplane = win.tk.splitlist(file_path_Inplane)
#Open to select multiple files for outplane
file_path_Ooplane = tkFileDialog.askopenfilename(initialdir=initial_dir, title="Select Out of Plane Files", multiple = 1)
if file_path_Ooplane != "":
pass
else:
print "You didn't open anything!"
InputfilesListOoplane = file_path_Ooplane#master.tk.splitlist(file_path_Ooplane)
for file_path_IP in InputfilesListInplane:
Name = call_Controller(file_path_IP, InputfilesListOoplane)
print "Done " + Name
I'm not sure what "in multiple outplane data" might be but the error message explains quite clearly:
'C:/Users/zhenhui/Desktop/bye1.txt C:/Users/zhenhui/Desktop/hello1.txt'
is not a valid file name. For me, this looks like two file names that you appended with a space between them.
When you open files, neither Python nor the OS will try to read your mind. Use a single file name per operation.
Prolem here:
IOError: [Errno 22] invalid mode ('r') or filename: u'C:/Users/zhenhui/Desktop/bye1.txt C:/Users/zhenhui/Desktop/hello1.txt'
Check correct place of delivery your path.
Next potential pronlem here initial_dir = "C:\VSM". Must initial_dir = "C:\\VSM" or initial_dir = "C:/VSM". Furthermore use path-related functions from os.path module.

Categories