简体   繁体   中英

Python closes after running program with writing to file

Python keeps closing after I try and run a script. It runs fine and works perfect in my IDE, but when I run the.py from file explorer, it immediately closes, and doesn't write to the file as directed. I want the program to delete all text on the file, then write 'ToWrite' 4 times.

my_file = open(r"C:\Users\shady\Desktop\copy\python\myfile.txt", "w")
my_file.write("")
my_file.close()

time = [1,1,1,1]
ToWrite = "hello\n"
for x in time:
    my_file = open("myfile.txt", "a")
    my_file.write(ToWrite)
    my_file.close()

I want the program to delete all text on the file, then write 'ToWrite' 4 times.

I tried removing these lines of code from my larger project, and it ran with no isues.

I presume you are running this via the command prompt, and so should be able to see the error message. Please post that also. The main problem is that you are not escaping the backslash. Try this:

my_file = open("C:\\Users\\shady\\Desktop\\copy\\python\\myfile.txt", "w")

or this:

my_file = open("C:/Users/shady/Desktop/copy/python/myfile.txt", "w")

or this:

import os
filepath = os.sep.join(["C:", "Users", "shady", "Desktop", "copy", "python", "myfile.txt"])
my_file = open(filepath,"w")

If you are not familiar with the command prompt. Open the Windows Start menu and type cmd then select the cmd prompt. Inside here use cd to change the directory to where your python program is located, then run

py yourprogram.py

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM