所以!
我在文件夹和文本文件中有一堆PDF文件。
任务如下:逐行将文本文件和PDF文件的大小附加到文件中。
我还没有发现这样的问题,所以我需要您的帮助!
有人有简单的解决方法吗?
首先,由于您需要一个简单的解决方案,所以我要指出的是,如果您使用的是类似于Linux Shell的任何东西,则可以在命令行中完成,就像这样:
$ ls -al
total 5968
drwxr-xr-x 5 edwsmith staff 160 May 20 10:01 .
drwxr-xr-x 37 edwsmith staff 1184 May 20 09:56 ..
-rw-r--r-- 1 edwsmith staff 1024000 May 20 09:57 1.pdf
-rw-r--r-- 1 edwsmith staff 2024000 May 20 09:57 2.pdf
-rw-r--r-- 1 edwsmith staff 39 May 20 10:01 textfile.txt
$ cat textfile.txt
this is some existing text in the file
$ ls -l *.pdf | cut -d ' ' -f 8,12 >> textfile.txt
$ cat textfile.txt
this is some existing text in the file
1024000 1.pdf
2024000 2.pdf
在python中执行此操作需要做更多的工作,但不多:
import os
import glob
textfilename = 'textfilename'
with open(textfilename, 'a') as textfile: # Open the text file for appending
for filename in glob.iglob('*.pdf'): # For every file in the current directory matching '*.pdf'
stat = os.stat(filename) # os.stat gets various file statistics
filesize = stat.st_size
textfile.write(f'File {filename} has size {filesize} bytes\n') # \n means newline
import os
with open(textfile,'a') as f:
for item in os.listdir(os.path.abspath(os.curdir)):
if item.endswith('.pdf'):
f.write(str(os.path.getsize(item))
import os
directory = '/home/user/Documents/'
with open("hello.txt", "a") as f:
for file in os.listdir(directory):
if file.endswith(".pdf"):
size = os.path.getsize(directory + file)
f.write(str(size))