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.
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: