with open python code example

Example 1: open applications by python

dir = 'C:\\myprogram.exe'

import os
os.startfile(dir)
os.system(dir)

import subprocess
subprocess.Popen([dir])
subprocess.call(dir)

Example 2: python write to file

with open(filename,"w") as f:
  f.write('Hello World')

Example 3: python with file.open

# Reference https://docs.python.org/3/library/functions.html#open

# Method 1
file = open("welcome.txt", "r") # mode can be r(read) w(write) and others 
data = file.read()
file.close()

# Method 2 - automatic close
with open("welcome.txt") as infile:
  data = file.read()

Example 4: python file reading

fin = open("NAME.txt", 'r')
body = fin.read().split("\n")
line = fin.readline().strip()

Example 5: with open python types

'r'	Open a file for reading. (default)
'w'	Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
'x'	Open a file for exclusive creation. If the file already exists, the operation fails.
'a'	Open for appending at the end of the file without truncating it. Creates a new file if it does not exist.
't'	Open in text mode. (default)
'b'	Open in binary mode.
'+'	Open a file for updating (reading and writing)

Example 6: python file open

#there are many modes you can open files in. r means read.
file = open('C:\Users\yourname\files\file.txt','r')
text = file.read()

#you can write a string to it, too!
file = open('C:\Users\yourname\files\file.txt','w')
file.write('This is a typical string')

#don't forget to close it afterwards!
file.close()

Tags:

Misc Example