把目录中每个文件的“头”?
问题描述:
我正在处理大文件,这里我的问题是双重的。把目录中每个文件的“头”?
猛砸 - 出于测试目的,我想在一个给定的目录中的所有文件遍历,取
Head
每个文件(比如说Head 10000
),并留下了各自的简化版本。无论是在 同一目录或另一个它并不重要,虽然我 假设相同将是首选。Python3 - 如何以编程方式执行此操作?我想我需要使用os module?
答
试试这个使用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,看http://docs.python.org/2/library/subprocess.html如果您想使用shell代码。
答
缩略以这种方式在当前目录中的所有文件,可以使用:
for f in *; do [[ $f != *.small ]] && head -n 10000 "$f" > "$f".small; done
文件将与.small
的后缀。
从蟒蛇为此,
import os
os.system('for f in *; do [[ $f != *.small ]] && head -n 10000 "$f" > "$f".small; done')
+1
'os.system()'在2013年不推荐使用。使用'subprocess'代替 –
答
击:
的最直接方式:
#!/usr/bin/env bash
DEST=/tmp/
for i in *
do
head -1000 "${i}" > ${DEST}/${i}
done
如果你有大量的文件,你可以运行多个通过生成一个文件列表,将它们分离出来,并对每个列表运行循环。
的Python:
假设我们的目标是不产卵shell会话执行外部二进制文件,像“头”,这是我会怎么做呢。
#!/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()
不错,bash部分工作。不得不将'cp'$ 1“$ i.tail”'改为'cp“$ 1”“i.tail”' – Houdini
Post updated,done –
我不想链接到'python'文档,因为我知道'python' ''''''''''''''''''''''''我找到了一个Python解决方案,你的bash可以工作,但是不需要python.Think Tang的Python可以工作,但不是他的bash解决方案,我希望我可以给予50% – Houdini