Create file and write content in it
(dest, content, overwrite=True, append=False)
| 426 | |
| 427 | # noinspection PyArgumentList |
| 428 | def writefile(dest, content, overwrite=True, append=False): |
| 429 | """ |
| 430 | Create file and write content in it |
| 431 | """ |
| 432 | content = to_utf8(content) |
| 433 | if is_PY3 and not isinstance(content, bytes): |
| 434 | content = bytes(content, 'utf-8') |
| 435 | if not os.path.exists(dest): |
| 436 | logger.debug(' * Writing %s ... ', dest, extra=dict(continued=True)) |
| 437 | with open(dest, 'wb') as f: |
| 438 | f.write(content) |
| 439 | make_executable(dest) |
| 440 | logger.debug('done.') |
| 441 | return |
| 442 | else: |
| 443 | with open(dest, 'rb') as f: |
| 444 | c = f.read() |
| 445 | if content in c: |
| 446 | logger.debug(' * Content %s already in place', dest) |
| 447 | return |
| 448 | |
| 449 | if not overwrite: |
| 450 | logger.info(' * File %s exists with different content; ' |
| 451 | ' not overwriting', dest) |
| 452 | return |
| 453 | |
| 454 | if append: |
| 455 | logger.info(' * Appending data to %s', dest) |
| 456 | with open(dest, 'ab') as f: |
| 457 | f.write(content) |
| 458 | return |
| 459 | |
| 460 | logger.info(' * Overwriting %s with new content', dest) |
| 461 | with open(dest, 'wb') as f: |
| 462 | f.write(content) |
| 463 | |
| 464 | |
| 465 | def callit(cmd, show_stdout=True, in_shell=False, |
no test coverage detected