我有一个带pdf文件的文件夹,并且有一个文本文件:helloworld.txt和另一个txt文件description.txt
helloworld.txt默认为空。description.txt包含文件的描述。每行一个描述。
我希望helloworld.txt中的每一行都包含pdf文件的名称,文件的大小以及文件的描述。
因此,每一个helloworld.txt行如下所示:{filename} {filesize} {description}
文件夹中有很多行,例如pdf元素。
我有以下代码段:
import os
import glob
textfilename = 'helloworld.txt'
descriptiontext = open("description.txt", 'r')
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/1024/1024
filesize = round(filesize,2)
description = descriptiontext.readline()
textfile.write(f'{filename} {filesize} {description} \n') # \n means newline
该脚本几乎可以正常运行。 {filename} {filesize} {description}在合适的位置。
[问题:pdf文件夹设置为按修改时间排序(我从网站下载的方式),看起来像在文件夹中(Lubuntu 20.04 LTS),但是在运行脚本后,{filename}序列与helloworld.txt文件中文件夹的顺序。
如何修改代码以按照相同的顺序在helloworld.txt中写入{filename},就像在文件夹顺序中按修改时间排序?
首先,由于您需要一个简单的解决方案,所以我要指出的是,如果您使用的是类似于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))