Skip to content

Instantly share code, notes, and snippets.

@danield137
Last active May 6, 2019 10:07
Show Gist options
  • Select an option

  • Save danield137/0befa1cf287c492d4c95b4f91d8362ff to your computer and use it in GitHub Desktop.

Select an option

Save danield137/0befa1cf287c492d4c95b4f91d8362ff to your computer and use it in GitHub Desktop.
Copy first lines of every file in folder
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