write file to new directory python code example
Example 1: python write to file
file = open(“testfile.txt”,”w”)
file.write(“Hello World”)
file.write(“This is our new text file”)
file.write(“and this is another line.”)
file.write(“Why? Because we can.”)
file.close()
Example 2: copy file in python3
import shutil
original = r'original path where the file is currently stored\file name.file extension'
target = r'target path where the file will be copied\file name.file extension'
shutil.copyfile(original, target)
Example 3: python loop opening file from directory
basepath = "pathtodir/DataFiles/"
for filename in os.listdir(basepath):
if filename.endswith(".log"):
print(os.path.join("./DataFiles", filename))
with open(basepath + filename) as openfile:
for line in openfile:
........