How do I convert a file from plain text to a list variable? - python-3.x

I have a python program and it seems that whenever I open it with this line of code active:
content = open('Word_list.txt').read().splitlines() it just closes itself (by open I mean double clicking it from file explorer, works fine every other way). I tried with a small list variable and my program works file when it's like that so I need to convert a 4MB file (4,250,000 lines) into a python list variable. Is there any way to do that and will there be any slowdowns because of what i'm doing here?
Oh, and I should mention that I tried other ways of importing the text file (for loops and whatnot) and that seemed to crash instantly too. Thanks!

Because you are running it through Explorer the window is closing before you can see an error message, so add some error handling code:
try:
content = open('Word_list.txt').read().splitlines()
except Exception as exc:
import traceback
print(traceback.format_exc())
input()

I managed to use Notepad++ and their macro system to put the required " ",'s over all of the words, completing my objecting using another program instead of python.

Related

Python file immediately closes

As an assignment for one of my classes, the professor had us download a file containing python code as well as a couple of text files that the python code will analyze.
The problem is, when I click to open the python file, the command window opens, then immediately closes. I can get it to stop from closing if I click on it fast enough, but that stops the code from loading, and any keystroke causes it to close again.
It's the same file every other student downloaded and used with no issue. I've tried re-downloading the file, re-installing python, even trying on a different computer. I've also tried opening it by entering the path file name in the command window with no success. Also no luck trying it in Jupyter Notebook or CodeLab. (And of course, no luck experimenting with the slew of possible solutions on previous Stack Overflow, Reddit, etc. questions).
Any ideas on the potential cause and/or solution?
Edit: cause unknown, but the solution was opening the file with Sypder console.
the file closes immediately because It ended and returned 0, to stop that from happening you can add at the end of the python code something like that:
ending = input("press key to exit")
or just import time and use
time.sleep(5)
you can open your file in the cmd/terminal window and you will be able to see the results

How to get rid of the error 'EOFError: EOF when using input() after having used sys.stdin.readlines() in a different function?

I am trying to replicate an Excel VBA macro to Python for the sake of learning a new programming language and I am stuck at a point which Google alone is not helping (I guess I do not even know what to look for). Could you please give it a try?
What I expect the program to do:
When running the user should be prompted with a few options and if the input is 0 then it should ask for a multi line input containing a full HTML source code from this website Steam Tools
After the input the user is expected to hit CTRL+D / CTLR+Z to confirm there is nothing else to add (I think the problem is here, maybe it is not able to "clear" the EOF error while using input() again?)
Then as an ouput the program should return the first 10 rows delimited by comma and create another input() to avoid the window to autoclose.
What the issue is:
When I run it from the desktop (double cliking the .py file) it autocloses withouth creating the last input().
When I run it from PyCharm it runs OK and the last input remains waiting for user action. However, it does dump an error like this:
File "D:/Stuff/_root/py/Steam/steam_cards_manager.py", line 51, in z_parse_tbody
input('\nCopy the program output and type Back:') EOFError: EOF when reading a line
Any feedback is appreciated as I don't know if I am doing things in an easy / effcient way.
I've upload my .py file and also a sample HTML to make it easier to replicate the issue, hope it helps.
https://github.com/brmenezewe/db
It turned out that I had to replace the CTRL+D shortcut by a "trigger" word that when sent via a single input() it breaks the While loop and joins the inputs previously received:
def z_input_lines():
lines = []
while True:
line = input()
if not line or line.lower() != "go":
lines.append(line)
else:
break
return "".join(lines)

Why do I get no error when running the same Python script on multiple terminals at the same time?

I know from experience that if I try to open the same file in Vim in multiple terminals at the same time, I get an error. (Maybe because of temporary files?)
And I know from experience that if I open a text file in Python and read through it, I have to reset the pointer when I'm done.
But I've found that if I run the same Python script in multiple terminals at the same time, I don't get any error; it just successfully runs the script in both. How does this work? Doesn't Python need to read my script from the beginning in order to run it? Is the script copied to a temporary file, or something?
I know from experience that if I try to open the same file in Vim in multiple terminals at the same time, I get an error.
That's not actually true. Vim actually will let you open the same file in multiple terminals at the same time; it's just that it gives you a warning first to let you know that this is happening, so you can abort before you make changes. (It's not safe to modify the file concurrently in two different instances of Vim, because the two instances won't coordinate at all.)
Furthermore, Vim will only give you this warning if you try to open the same file for editing in multiple terminals at the same time. It won't complain if you're just opening the file for reading (using the -R flag).
And I know from experience that if I open a text file in Python and read through it, I have to reset the pointer when I'm done.
That's not exactly true, either. If you make multiple separate calls to open, you'll have multiple separate file objects, and each separately maintains its position in the file. So something like
with open('filename.txt', 'r') as first:
with open('filename.txt', 'r') as second:
print(first.read())
print(second.read())
will print the complete contents of filename.txt twice.
The only reason you'd need to reset the position when you're done reading a file is if you want to use the same file object to read the file again, or if you've opened the file in read/write mode (r+ rather than r) and you now want to switch from reading to writing.
But I've found that if I run the same Python script in multiple terminals at the same time, I don't get any error; it just successfully runs the script in both. How does this work? Doesn't Python need to read my script from the beginning in order to run it? Is the script copied to a temporary file, or something?
As I think should now be clear — there's no problem here. There's no reason that two instances of Python can't both read the same script file at the same time. Linux allows that. (And in fact, if you delete the file, Linux will keep the file on disk until all programs that had it open have either closed it or exited.)
In fact, there's also no reason that two processes can't write to the same file at the same time, though here you have to be very careful to avoid the processes causing problems for each other or corrupting the file.
terminal is just running the command you said it to execute, there is no pointer or anything
you jus

batch file to close cmd when program not found

I am writing a python program which takes input from the user then create a batch file and open that program and I want that if program not found then it returns that error to python and close the popup
Windows cannot find 'room'. make sure you type correctly, and then try again.
and cmd.
I don't have any idea how to solve this problem.
def batch(text):
bat_file = open("hello.bat","w")
bat_file.write("start "+text)
bat_file.close()
os.startfile("hello.bat")
As I mentioned above I want to close the popup and cmd.

Why isn't 'for line in file' copying all lines in my text file?

I wrote some code to pull certain lines from a large text file and noticed some strange things missing, so I ran the following code to make sure the for loop was actually hitting every line in the file:
xf=open("bigFile.txt", r)
xxf=open("newFile.txt",w)
for line in xf:
xxf.write(line)
This ends up not copying all the lines for some reason. Could anyone tell me what I'm not understanding or doing wrong? It ends up only making a file about 60-70% as big as it should be? Any insight would be greatly appreciated.
EDIT: Thanks for the input skrrgwasme & Shreevardhan. To clarify, my ultimate goal is not just to copy the file, in my working code I put some comparison operators before writing the line, for example:
for line in xf:
firstChar=line[:1]
if firstChar==1:
xxf.write(line)
That is why I am using the "for line in file". Should I do this some other way?
To copy a file, it's better to use functions from shutil module like copyfile(), copy(), or copy2().
For example
from shutil import copyfile, copy2
copyfile('bigFile.txt', 'newFile.txt')
or
copy2('bigFile.txt', 'newFile.txt')
You need to close your file. There's no guarantee that buffers you're writing into are being flushed to disk before your script exits. You can do this very easily by using a context manager:
with open("bigFile.txt") as xf, open("newFile.txt", "w") as xxf:
for line in xf:
xxf.write(line)
In your current code, you would write xf.close() and xxf.close(), but using a context manager like this will handle it for you, and even close the files if an exception occurs.
Also, if you really are simply copying the file, you can also use shutil.copyfile().

Resources