Videos
I have never used python before, but I need it to follow some instructions. I am supposed to "Copy the code sample and save it in a file named example.py." I have the code sample, but how do I save it in a file? Do you do that in python?
You could just use a multiline string:
Copyimport os
filepath = os.getcwd()
def MakeFile(file_name):
temp_path = filepath + file_name
with open(file_name, 'w') as f:
f.write('''\
def print_success():
print "sucesss"
''')
print 'Execution completed.'
If you like your template code to be indented along with the rest of your code, but dedented when written to a separate file, you could use textwrap.dedent:
Copyimport os
import textwrap
filepath = os.getcwd()
def MakeFile(file_name):
temp_path = filepath + file_name
with open(file_name, 'w') as f:
f.write(textwrap.dedent('''\
def print_success():
print "sucesss"
'''))
print 'Execution completed.'
Copylines = []
lines.append('def print_success():')
lines.append(' print "sucesss"')
"\n".join(lines)
If you're building something complex dynamically:
Copyclass CodeBlock():
def __init__(self, head, block):
self.head = head
self.block = block
def __str__(self, indent=""):
result = indent + self.head + ":\n"
indent += " "
for block in self.block:
if isinstance(block, CodeBlock):
result += block.__str__(indent)
else:
result += indent + block + "\n"
return result
You could add some extra methods, to add new lines to the block and all that stuff, but I think you get the idea..
Example:
Copyifblock = CodeBlock('if x>0', ['print x', 'print "Finished."'])
block = CodeBlock('def print_success(x)', [ifblock, 'print "Def finished"'])
print block
Output:
Copydef print_success(x):
if x>0:
print x
print "Finished."
print "Def finished."
I have watched many a YouTube video, but alas, it just confused me more. What is the python equivalent to things like File.WriteLine in c#?
Thanks in advance.
This should be as simple as:
with open('somefile.txt', 'a') as the_file:
the_file.write('Hello\n')
From The Documentation:
Do not use
os.linesepas a line terminator when writing files opened in text mode (the default); use a single'\n'instead, on all platforms.
Some useful reading:
- The
withstatement open()'a'is for append, or use'w'to write with truncation
os(particularlyos.linesep)
You should use the print() function which is available since Python 2.6+
from __future__ import print_function # Only needed for Python 2
print("hi there", file=f)
For Python 3 you don't need the import, since the print() function is the default.
The alternative in Python 3 would be to use:
with open('myfile', 'w') as f:
f.write('hi there\n') # python will convert \n to os.linesep
Quoting from Python documentation regarding newlines:
When writing output to the stream, if newline is
None, any'\n'characters written are translated to the system default line separator,os.linesep. If newline is''or'\n', no translation takes place. If newline is any of the other legal values, any'\n'characters written are translated to the given string.
See also: Reading and Writing Files - The Python Tutorial
Every time you enter and exit the with open... block, you're reopening the file. As the other answers mention, you're overwriting the file each time. In addition to switching to an append, it's probably a good idea to swap your with and for loops so you're only opening the file once for each set of writes:
with open("output.txt", "a") as f:
for key in atts:
f.write(key)
You need to change the second flag when opening the file:
wfor only writing (an existing file with the same name will be erased)aopens the file for appending
Your code then should be:
with open("output.txt", "a") as f: