Last active
May 6, 2019 10:07
-
-
Save danield137/0befa1cf287c492d4c95b4f91d8362ff to your computer and use it in GitHub Desktop.
Copy first lines of every file in folder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| extension = '.csv' | |
| files = [f for f in os.listdir() if f.endswith(extension)] | |
| target_dir = 'samples' | |
| lines_to_copy = 1000 | |
| os.mkdir(target_dir) | |
| for file in files: | |
| source_path = os.path.join(os.getcwd(), file) | |
| target_path = os.path.join(os.getcwd(), target_dir, file) | |
| with open(source_path, 'r') as source_f: | |
| with open(target_path, 'w+') as target_f: | |
| for _ in range(lines_to_copy): | |
| try: | |
| line = source_f.readline() | |
| if not line: | |
| break | |
| target_f.write(line) | |
| except Exception as ex: | |
| print(ex) | |
| target_f.flush() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment