I am new in programming. Just bought a book for beginners in Python. In it I got this code:
name = input("name")
email = input("whats ure email:)
favoriteband = input("ure fav band")
outputString = name + "|" email + "|" + favoriteband
fileName = name + ".txt"
file = open(fileName, "wb")
file.write (outputString)
print (outputString , " saved in ", fileName)
file.close ()
According to book its fine but I got this error:
TypeError: a bytes-like object is required, not 'str'
I got no clue how to fix it and book isn't explaining this as well.
Let's go through this:
name = input("Your name: ")
email = input("Your email: ")
The close quotes are needed as has been pointed out.
outputString = name + "|" + email + "|" + favoriteband
outputString was missing a + before email
Finally, we need to rewrite you file management:
with open(fileName, "a") as file:
file.write (outputString)
print (outputString , " saved in ", fileName)
Writing this as a with statement guarantees it will close. Using open(..., "a") opens the file in "append" mode and lets you write multiple strings to a file of the same name.
Finally, if I can editorialize, I am not a fan of this book so far.
Edit: here is the whole code with fixes, in hopes of getting you there.
name = input("name")
email = input("whats ure email:")
favoriteband = input("ure fav band")
outputString = name + "|" + email + "|" + favoriteband
fileName = name + ".txt"
with open(fileName, "a") as file:
file.write (outputString)
print (outputString , " saved in ", fileName)
You can verify it works with:
with open(fileName, "r") as file:
print(file.read())
I did some editing (closing quotes and a missing +):
name = input("name:")
email = input("whats ure email:")
favoriteband = input("ure fav band:")
outputString = name + " | " + email + " | " + favoriteband
fileName = name + ".txt"
file = open(fileName, "w") #opened in write mode but not in binary
file.write (outputString)
print (outputString , " saved in ", fileName)
file.close()
You're getting that error because you're writing in binary mode, hence the b in wb for
file = open(fileName, "wb")
Try this instead :
file = open(fileName, "w")
Related
Been trying to write my PYTHON code but it will always output the file with a blank line at the end. Is there a way to mod my code so it doesn't print out the last blank line.
def write_concordance(self, filename):
""" Write the concordance entries to the output file(filename)
See sample output files for format."""
try:
file_out = open(filename, "w")
except FileNotFoundError:
raise FileNotFoundError("File Not Found")
word_lst = self.concordance_table.get_all_keys() #gets a list of all the words
word_lst.sort() #orders it
for i in word_lst:
ln_num = self.concordance_table.get_value(i) #line number list
ln_str = "" #string that will be written to file
for c in ln_num:
ln_str += " " + str(c) #loads line numbers as a string
file_out.write(i + ":" + ln_str + "\n")
file_out.close()
Output_file
Line 13 in this picture is what I need gone
Put in a check so that the new line is not added for the last element of the list:
def write_concordance(self, filename):
""" Write the concordance entries to the output file(filename)
See sample output files for format."""
try:
file_out = open(filename, "w")
except FileNotFoundError:
raise FileNotFoundError("File Not Found")
word_lst = self.concordance_table.get_all_keys() #gets a list of all the words
word_lst.sort() #orders it
for i in word_lst:
ln_num = self.concordance_table.get_value(i) #line number list
ln_str = "" #string that will be written to file
for c in ln_num:
ln_str += " " + str(c) #loads line numbers as a string
file_out.write(i + ":" + ln_str)
if i != word_lst[-1]:
file_out.write("\n")
file_out.close()
The issue is here:
file_out.write(i + ":" + ln_str + "\n")
The \n adds a new line.
The way to fix this is to rewrite it slightly:
ln_strs = []
for i in word_lst:
ln_num = self.concordance_table.get_value(i) #line number list
ln_str = " ".join(ln_num) #string that will be written to file
ln_strs.append(f"{i} : {ln_str}")
file_out.write('\n'.join(ln_strs))
Just btw, you should actually not use file_out = open() and file_out.close() but with open() as file_out:, this way you always close the file and an exception won't leave the file hanging
I am made a file where i can reference functions and i thought that it would be fun to make a program to add text to the file, and when i try to open the file, it doesn't show any errors, but when i go and check the file there's nothing there.
My code:
ime_funk = input("Ime funkcije: ")
x = 0
funk = ""
while True:
vseb_funk = input("Kopiraj eno, pa po eno vrstico funkcije, ko si končal napiši končano: ")
if vseb_funk == "končano":
break
else:
funk += "\n "+vseb_funk
mark = open("test.txt", "a")
mark.write("\n" + ime_funk + "\n" + funk)
Don't pay attention to the variable names and strings, as that's not important.
Also I am using replit if that's important.
I have no idea why it doesn't work.
i have tried mark = open("test.txt", "w") but same story.
you need to add this line to your code
mark.close()
or what you can do I replace this part of the code
mark = open("test.txt", "a")
mark.write("\n" + ime_funk + "\n" + funk)
with this code:
with open("test.txt", "a") as mark:
mark.write("\n" + ime_funk + "\n" + funk)
A file write in python does not happen untill you call file.flush(). This is usually called automatically when you close the file but in your example you are never closing the file. Try:
ime_funk = input("Ime funkcije: ")
x = 0
funk = ""
while True:
vseb_funk = input("Kopiraj eno, pa po eno vrstico funkcije, ko si končal napiši končano: ")
if vseb_funk == "končano":
break
else:
funk += "\n "+vseb_funk
mark = open("test.txt", "a")
mark.write("\n" + ime_funk + "\n" + funk)
mark.close()
or even better try using the with statement:
with open("test.txt", "a") as mark:
mark.write("\n" + ime_funk + "\n" + funk)
this way close() is called automatically
I made a program which has one function. This function has a file as an input and function writes result to output. I need to test if the my result is the same as expected. Below you can find a code of a program:
import os
def username(input):
with open(input, 'r') as file:
if os.stat(input).st_size == 0:
print('File is empty')
else:
print('File is not empty')
for line in file:
count = 1
id, first, middle, surname, department = line.split(":")
first1 = first.lower()
middle1 = middle.lower()
surname1 = surname.lower()
username = first1[:1] + middle1[:1] + surname1
username1 = username[:8]
if username1 not in usernames:
usernames.append(username1)
data = id + ":" + username1 + ":" + first + ":" + middle + ":" + surname + ":" + department
else:
username2 = username1 + str(count)
usernames.append(username2)
data = id + ":" + username2 + ":" + first + ":" + middle + ":" + surname + ":" + department
count += 1
with open("output.txt", "a+") as username_file:
username_file.write(data)
usernames = []
if __name__ == '__main__':
username("input_file1.txt")
username("input_file2.txt")
username("input_file3.txt")
with open("output.txt", "a+") as username_file:
username_file.write("\n")
How do I write an unittest on this type of program? I tried this but it gave me this error "TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper" . Code of my test is below:
import unittest
import program.py
class TestProgram(unittest.TestCase):
def test_username(self):
i_f = open("input_file1.txt", 'r')
result = program.username(i_f)
o_f = open("expected_output.txt", 'r')
self.assertEqual(result, o_f)
if __name__ == '__main__':
unittest.main()
I would be really happy if you could help me!!!
You didn't read the file, just pass the IO object.
Edit the TestProgram and add .read()
class TestProgram(unittest.TestCase):
def test_username(self):
i_f = open("input_file1.txt", 'r').read() # read the file
result = program.username(i_f)
o_f = open("expected_output.txt", 'r').read()
self.assertEqual(result, o_f)
you can also use with-as for automatic closing the file.
I have two files I want to open:
file = open('textures.txt', 'w')
file = open('to_decode.txt', 'w')
Then I want to write to both of them separately:
file.write("Username: " + username + " Textures: " + textures)
file.write(textures)
The first write thing is for the first open and the second is for the second.
How would I do this?
You are overwriting the file variable with the second open, so all the writes would be directed there. Instead, you should use two variables:
textures_file = open('textures.txt', 'w')
decode_file = open('to_decode.txt', 'w')
textures_file.write("Username: " + username + " Textures: " + textures)
decode_file.write(textures)
Name your file pointers two different things, i.e. not both "file".
file1 = open...
file2 = open...
file1.write...
file2.write...
Right now, the second "file" declaration you're making is over-writing the first one, so file only points to "to_decode.txt".
You can use "with" to avoid mentioning file.close() explicitly. Then You don't have to close it - Python will do it automatically either during garbage collection or at program exit.
with open('textures.txt', 'w') as file1,open('to_decode.txt', 'w') as file2:
file1.write("Username: " + username + " Textures: " + textures)
file2.write(textures)
Just give them different names:
f1 = open('textures.txt', 'w')
f2 = open('to_decode.txt', 'w')
f1.write("Username: " + username + " Textures: " + textures)
f2.write(textures)
As others have mentioned, file is the name of a built-in function so using that name for your local variable is a bad choice.
You need to use two different variables, as #Klaus says, to create two different, distinct handles to which you can push operations. So,
file1 = open('textures.txt', 'w')
file2 = open('to_decode.txt', 'w')
then
file1.write("Username: " + username + " Textures: " + textures)
file2.write(textures)
I am new to Python and I am trying to check for nulls in the csv I am processing. I am using a DictReader object with key pair values. I am using the key pair values in the for loop to print out the information(kml in this instance).
I go to run the program and it is not liking my variable assignment. Here is the error I am receiving.
File "./csvtokml3.py", line 31
Latvariable = str(row["lat_degrees"]),Longvariable = str(row["lon_degrees"])
SyntaxError: can't assign to function call
Here is the code for the program.
#!/usr/bin/python
#
#
#
import csv
#Input the file name.
fname = raw_input("Enter file name WITHOUT extension: ")
data = csv.DictReader(open(fname + '.csv'), delimiter = ',')
#Open the file to be written.
f = open('csv2kml.kml', 'w')
#Writing the kml file.
f.write("<?xml version='1.0' encoding='UTF-8'?>\n")
f.write("<kml xmlns='http://www.opengis.net/kml/2.'>\n")
f.write("<Document>\n")
f.write(" <name>" + fname + '.kml' +"</name>\n")
for row in data:
f.write(" <Placemark>\n")
f.write(" <name>" + str(row["station"]) + "</name>\n")
### f.write(" <description>" + str(row[0]) + "</description>\n")
f.write(" <Point>\n")
#Check for nulls for lat and long
Latvariable = str(row["lat_degrees"]), Longvariable = str(row["lon_degrees"])
if Latvariable !=null and Longvariable !=null:
f.write(" <coordinates>" + str(row["lat_degrees"]) + "," + str(row["lon_degrees"]) + "</coordinates>\n")
f.write(" </Point>\n")
f.write(" </Placemark>\n")
f.write("</Document>\n")
f.write("</kml>\n")
f.close()
print "File Created. "
print "Press ENTER to exit. "
raw_input()
Your syntax is incorrect, you wanted:
Latvariable, Longvariable = str(row["lat_degrees"]), str(row["lon_degrees"])
instead to assign multiple values to multiple names. Alternatively, put the two statements on separate lines:
Latvariable = str(row["lat_degrees"])
Longvariable = str(row["lon_degrees"])
You cannot combine multiple assignment statements with commas like you tried; that works in JavaScript but not in Python.