我正在处理大文件,我的问题有两个。
Bash - 出于测试目的,我想迭代给定目录中的每个文件,获取每个文件的
Head
(比如 Head
10000
),并留下每个文件的精简版本。要么在
同一目录或另一个目录并不重要,尽管我
假设同样的会是首选。Python3 - 如何以编程方式执行此操作?我想我需要使用 os 模块?
使用 shell 尝试一下:
for i in *; do
cp "$i" "$i.tail"
sed -i '10001,$d' "$i.tail"
done
或者简单地:
for i in *; do
sed '10001,$d' "$i" > "$i.tail"
done
或:
for i in *; do
head -n 1000 "$i" > "$i.tail"
done
对于 python,如果您想使用 shell 代码,请参阅 http://docs.python.org/2/library/subprocess.html。
重击:
最直接的方法:
#!/usr/bin/env bash
DEST=/tmp/
for i in *
do
head -1000 "${i}" > ${DEST}/${i}
done
如果您有大量文件,您可以通过生成文件列表、将它们拆分并针对每个列表运行循环来运行多个作业。
Python:
假设目标是不生成 shell 会话来执行外部二进制文件,例如“head”,这就是我的做法。
#!/usr/bin/env python
import os
destination="/tmp/"
for file in os.listdir('.'):
if os.path.isfile( file ):
readFileHandle = open(file, "r")
writeFileHandle = open( destination + file , "w")
for line in range( 0,1000):
writeFileHandle.write(readFileHandle.readline())
writeFileHandle.close()
readFileHandle.close()
怎么样:
ls | xargs -i head {}
要以这种方式缩写当前目录中的所有文件,您可以使用:
for f in *; do [[ $f != *.small ]] && head -n 10000 "$f" > "$f".small; done
文件将以
.small
为后缀。
要从 python 中执行此操作,
import os
os.system('for f in *; do [[ $f != *.small ]] && head -n 10000 "$f" > "$f".small; done')