我有多个子文件夹,每个子文件夹里面都有2个图像。
我的目标是拍摄每张图片(文件)并替换为%s
并写入同一文件夹中的latex.txt
。并为每个文件夹执行此操作。
到目前为止,我可以在每个文件夹中创建.txt
文件并在其上书写。
但是,我也无法用图片名称替换%s
,我的.txt
文件没有写入新行\n
import os
walk_dir = 'C:/Users/xx/Desktop/main/'
for root, subdirs, files in os.walk(walk_dir):
list_file_path = os.path.join(root, 'latex.txt')
with open(list_file_path, 'wb') as list_file:
all_image = []
for filename in files:
all_files = []
all_image.append(filename)
file_path = os.path.join(root, filename)
#print(all_image)
list_file.write(("\\documentclass{article} \n" \
"\\usepackage[utf8]{inputenc} \n" \
"\\usepackage{graphicx} \n" \
"\n" \
"\\usepackage{subcaption} \n " \
"\n" \
"\\hspace*{-3cm} \n" \
"\\begin{subfigure}{0.6\\textwidth} \n" \
"\centering \n" \
"\includegraphics[width=1\linewidth]{%s} \n" \
"\label{fig:sfig1} \n" \
"\end{subfigure}%% \n" \
"\hspace{0.5in} \n" \
"\\begin{subfigure}{0.6\\textwidth} \n" \
"\centering \n" \
"\includegraphics[width=1\linewidth]{%s} \n" \
"\label{fig:sfig2} \n" \
"\end{subfigure} \n" \
"\label{fig:fig} \n" \
"\end{figure} \n" \
"\end{document}" % filename, filename).encode('utf-8'))
当我print(images)
时,我会在列表中为每个子文件夹获取图像。
"\end{document}" % filename).encode('utf-8'))
我在这里多次更改此代码,尝试从列表中获取值无效。我离开这里的是我的开始。这仅用%s
答案 0 :(得分:1)
这样的事情应该有效,你在我删除的LaTeX代码中也放错了\end{tabular}
。还可以按照您的要求收集images
变量中图像的文件路径。
import os
walk_dir = 'C:/Users/XX/Desktop/Main/'
for root, subdirs, files in os.walk(walk_dir):
list_file_path = os.path.join(root, 'latex.txt')
with open(list_file_path, 'w') as list_file:
images = []
for filename in files:
file_path = os.path.join(root, filename)
images.append(file_path)
if len(images) >= 1:
document = """
\\documentclass{article}
\\usepackage[utf8]{inputenc}
\\usepackage{graphicx}
\\usepackage{subcaption}
\\hfill & \\Large \\textbf{EXAMPLE}
\\hspace*{-3cm}
%s
\\end{document}
"""
figure = """
\\begin{subfigure}{0.6\\textwidth}
\\centering
\\includegraphics[width=1\\linewidth]{%s}
\\label{fig:sfig%d}
\\end{subfigure}
"""
separator = """
\\hspace{0.5in}
"""
figures = separator.join([figure % (image, i) for i, image in enumerate(images)])
list_file.write(document % figures)