Python Save to File

How to save a file to a specific directory in python?

Or if in Linux, try:

# To save to an absolute path.
r = requests.get(url)
with open('/path/I/want/to/save/file/to/file_name.pdf', 'wb') as f:
f.write(r.content)

# To save to a relative path.
r = requests.get(url)
with open('folder1/folder2/file_name.pdf', 'wb') as f:
f.write(r.content)

See open() function docs for more details.

Is there a way to save a file that is written by a python script, if the python script is killed before it is completed?

Using with should help here.

with open('newCsv.csv','w') as wr:
for i in range(100,000): # whatever range
num, name = 10000, 'hello' # The data extracted from the website
wr.writerow([num,name])
time.sleep(1)

Python script need to save output to text file

Just add

with open('textfile.txt', 'a+') as f:
f.write(ff)

a option is for appending to a file and + means that if the file is not there just create one with the specified name.

EDIT:

def on_press(key):
print ('{0} pressed'.format(key))
with open('textfile.txt', 'a+') as f:
f.write(ff)

EDIT 2:

def on_press(key):
print ('{0} pressed'.format(key))
k = key + '\n'
with open('textfile.txt', 'a+') as f:
f.write(key)

# and in get_titles()
ff= (moment2 + " : " + "Moved T0 : "+ new_title + '\n')
with open('textfile.txt', 'a+') as f:
f.write(ff)

Getting error after attempting to save file in python

The explanation is in the error :

FileNotFoundError: [Errno 2] No such file or directory: 'page/cropped-Jujutsu_kaisen-324x324-1.png'

With no more details, I would think that the directory page/ doesn't exist. Can you check this ?

the open() will create the file if it doesn't exist but not the parent directories.

If this is the problem, you can automatically create it like this:

dir = './page/'
os.makedirs(dir, exist_ok=True)
# Equivalent to :
# if (not os.path.isdir(dir)):
# os.mkdir(dir)

How to save python screen output to a text file

Let me summarize all the answers and add some more.

  • To write to a file from within your script, user file I/O tools that are provided by Python (this is the f=open('file.txt', 'w') stuff.

  • If don't want to modify your program, you can use stream redirection (both on windows and on Unix-like systems). This is the python myscript > output.txt stuff.

  • If you want to see the output both on your screen and in a log file, and if you are on Unix, and you don't want to modify your program, you may use the tee command (windows version also exists, but I have never used it)

  • Even better way to send the desired output to screen, file, e-mail, twitter, whatever is to use the logging module. The learning curve here is the steepest among all the options, but in the long run it will pay for itself.

Python: How to save files from folders and subfolders?

You can also use the pathlib module. It belongs to the python standard library as well, and, in my opinion, it may be a bit more intuitive to use than the os module.

import pathlib

def check_links_for_all_files(directory_name):
directories = [pathlib.Path(directory_name)]
for directory in directories:
for file in directory.iterdir():
if file.is_dir():
directories.append(file)
continue
print(file.name)
if file.suffix == '.html':
check_link(file)

saving file with format

The loop you're using is stitching together each of the elements in your users list so you end up with one long string in out_string. You probably introduced this loop after you got an error message when trying to save the list straight to a file.

Instead, and as suggested in the comments, you could save the data as JSON:

import json

users = ["50688", "212273", "4561843", "241851", "18624", "2872"]

with open("output_data.txt", "w") as out_file:
out_file.write(json.dumps(users))

output_data.txt will then contain:

["50688", "212273", "4561843", "241851", "18624", "2872"]

Note: this assumes that your original list is a list of strings, not integers (it wasn't clear from your question).

saving a variable as a text file name

This is the updated version of your code brother:

import random

def TheTeams (name):
file_name = "./" + name + ".txt" # This is the code that will create the file

with open(file_name, "a+") as t:
t.write (name)
t.write ("\n")

def NewPlayer (pname):
at = int(input("enter your players attack 1-10 "))
de = int(input("enter your players defence 1-10 "))
if at >10:
print ("NO")
at = random.randint(1,5)
if de >10:
print ("NO")
de = random.randint(1,5)

with open("the teamss.txt", "a") as t:
t.write (pname)
t.write (" ")
t.write ('%d' % at)
t.write (" ")
t.write ('%d' % de)
t.write ("\n")

for i in range (1,7):
pname = input("enter your players name ")
NewPlayer (pname)

print (""" Welcome to the ice hockey game
you will create your own team and try to score against your opponent
your teams are stored for future use

""")

n_team1 = input("player 1 do you want to create a new team ")

if n_team1 == "yes":
team = input("enter your team name ")
TheTeams (team)


Related Topics



Leave a reply



Submit