Write a file to a directory syntax
# Create filename variable for indirect or direct
file_to_save = os.path.join('filepath' , 'filename.ext')
# Using open( ) function w/ 'w' mode open(file_to_save, 'w')
IOError
Cause: Input/Output error meaning the directory does not exist w/i a given file path
Solution: Create said directory
Write data (“Hello World!”) to a file using open( )/close( )
# Create filename variable to a path to the file
file_to_save = os.path.join('directory' , 'filename.ext')
#Use open statement open the file as text outfile = open(file_to_save, 'w')
#Write some data to the file
outfile.write('Hello World!')
#close the file outfile.close( )
Write data (“H W!”) to a file using with
#Create filename variable to path to file
file_to_save = os.path.join('directory' , 'filename.ext')
# Using with open the file as text file with open(file_to_save , 'w') as txt_file :
(tab) #write data to file
(tab) txt_file.write(“Hello World”)
Newline escape sequence + example for 3 Items
\n
txt_file.write('Item1\nItem2\nItem3")
Output:
Item1
Item2
Item3