45 lines
		
	
	
		
			1.2 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
		
		
			
		
	
	
			45 lines
		
	
	
		
			1.2 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
|   | def write_to_file(filepath, content): | ||
|  |     """Writes content to a file.
 | ||
|  | 
 | ||
|  |     Args: | ||
|  |         filepath: The path to the file. | ||
|  |         content: The string to write to the file. | ||
|  |     Returns: | ||
|  |         True on success, False on failure.  Prints error messages. | ||
|  |     """
 | ||
|  |     try: | ||
|  |         with open(filepath, 'w') as f:  # 'w' mode overwrites, 'a' appends | ||
|  |             f.write(content) | ||
|  |         return True | ||
|  |     except OSError as e: | ||
|  |         print(f"Error writing to file {filepath}: {e}") | ||
|  |         return False | ||
|  | 
 | ||
|  | 
 | ||
|  | # Example usage: | ||
|  | filepath = "/tmp/file.dat"  # Or any path you want | ||
|  | content = "yooo" | ||
|  | 
 | ||
|  | if write_to_file(filepath, content): | ||
|  |     print(f"Successfully wrote '{content}' to {filepath}") | ||
|  | else: | ||
|  |     print("File write operation failed.") | ||
|  | 
 | ||
|  | 
 | ||
|  | # Example of appending: | ||
|  | def append_to_file(filepath, content): | ||
|  |     """Appends content to a file.""" | ||
|  |     try: | ||
|  |         with open(filepath, 'a') as f:  # 'a' mode appends | ||
|  |             f.write(content) | ||
|  |         return True | ||
|  |     except OSError as e: | ||
|  |         print(f"Error appending to file {filepath}: {e}") | ||
|  |         return False | ||
|  | 
 | ||
|  | # Example usage of append: | ||
|  | if append_to_file(filepath, "\nand more yooo"): # \n for a new line | ||
|  |     print("Successfully appended to the file.") | ||
|  | else: | ||
|  |     print("File append operation failed.") |