Please copy and paste your script using the back ticks `
found in the key just to the left of the number 1
of the keyboard. User three back ticks in series - each on their own line - both above and below the pasted code).
— First —
Add these two lines so that files created during testing will be placed on the desktop for easy reference:
import os
os.chdir(r'C:\Desktop')
This line:
nameagain = open("Names1.txt", "r")
Implies that the contents are of type str
since the file is of type .txt
.
A text file is not allowed to have type binary (bytes)
literals. However, when you execute this line:
print(nameagain.read())
You don’t get an error. This means that all of its contents are of type str
. In your
printout below, it implies type binary
per the b' prefix
, per this (only showing partial for brevity):
[b'LEGO 42164 Technic Racing Buggy Off Road Rally Vehicle Toy Race Car Building Set, ...']
However, we know that it cannot be type binary
since it is a text file
and text files can’t have byte literals
. This means that the information is actually all of type string str
. We also know this because you cannot write a list
to a text file.
For it to have been a binary file
, you would have had this instead:
nameagain = open("Names1.bin", "rb") # You don't have it like this, thus not binary type file
To test this, try this (then try again by removing the leading and ending double quotes – with the double quotes in place, it is all a string. Without the double quotes, it is a list with byte string literals
as elements - you should get an exception error
when removing them and retrying):
# Create a dummy string of type str that appears as type bytes when read and printed out.
strings_to_write = "[b'Today is Thursday!', b'Time to begin scripting Python', b'We are in the month of April', b'Looking forward to summer.']"
print(type(strings_to_write))
with open("handle4.txt", "w") as names_again:
names_again.write(strings_to_write)
with open("handle4.txt", "r") as names_again:
print(names_again.read())
— Second —
This here:
nameagainstr = list(nameagain)
Does not make sense since it is the handle of the list object created and NOT the actual contents
as per your implied printout at the bottom of your post. This is a bit misleading. Because then
you pass it to:
nameagainstr = list(nameagain) # You're creating a list of the object handle and not its strings
What you are looking for is instead:
with open('Names1.txt, 'r') as f:
namesagain = f.read()
or more concisely:
with open('Names1.txt, 'r') as f:
namesagain = f.read().split(',')
This applies to your other files as well. I have only highlighted this for one file for simplicity.
Test these snippets. At every turn, make sure you use the print statements to verify that your
script is progressing as expected.