M03 - Write to Files Flashcards
1
Q
Write a file to a directory syntax
A
# 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')
2
Q
IOError
A
Cause: Input/Output error meaning the directory does not exist w/i a given file path
Solution: Create said directory
3
Q
Write data (“Hello World!”) to a file using open( )/close( )
A
# 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( )
4
Q
Write data (“H W!”) to a file using with
A
#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”)
5
Q
Newline escape sequence + example for 3 Items
A
\n
txt_file.write('Item1\nItem2\nItem3") Output: Item1 Item2 Item3