读取多元素列表,查找元素并在 python 中打印出来
我正在编写一个 python 脚本来编写一个 tex 文件。但我必须使用另一个文件中的一些信息。这样的文件在每一行都有我需要使用的菜单名称。我使用 split 来为“菜单”的每一行提供一个列表。 例如,我必须用列表中的每个第二个元素编写一个部分,但运行后,我得到了任何东西,我能做什么?
这大致就是我正在做的事情:
texfile = open(outputtex.tex', 'w')
infile = open(txtfile.txt, 'r')
for line in infile.readlines():
linesplit = line.split('^')
for i in range(1,len(infile.readlines())):
texfile.write('\section{}\n'.format(linesplit[1]))
texfile.write('\\begin{figure*}[h!]\n')
texfile.write('\centering\n')
texfile.write('\includegraphics[scale=0.95]{pg_000%i.pdf}\n' %i)
texfile.write('\end{figure*}\n')
texfile.write('\\newpage\n')
texfile.write('\end{document}')
texfile.close()
顺便说一下,在 inclugraphics 行中,我必须将 pg_ 之后的数字从“0001”增加到“25050”。有什么线索吗??
我真的很感谢你的帮助。
I am writing a python script in order to write a tex file. But I had to use some information from another file. Such file has names of menus in each line that I need to use. I use split to have a list for each line of my "menu".
For example, I had to write a section with the each second element of my lists but after running, I got anything, what could I do?
This is roughly what I am doing:
texfile = open(outputtex.tex', 'w')
infile = open(txtfile.txt, 'r')
for line in infile.readlines():
linesplit = line.split('^')
for i in range(1,len(infile.readlines())):
texfile.write('\section{}\n'.format(linesplit[1]))
texfile.write('\\begin{figure*}[h!]\n')
texfile.write('\centering\n')
texfile.write('\includegraphics[scale=0.95]{pg_000%i.pdf}\n' %i)
texfile.write('\end{figure*}\n')
texfile.write('\\newpage\n')
texfile.write('\end{document}')
texfile.close()
By the way, in the inclugraphics line, I had to increace the number after pg_ from "0001" to "25050". Any clues??
I really appreciate your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不太明白你的问题。但我在您的代码中看到了几个错误。最重要的是:
一旦你读取了一个文件,它就消失了。 (您可以取回它,但在这种情况下没有意义。)这意味着第二次调用 readlines 不会产生任何结果,因此 len(infile.readlines()) == 0 。假设您在此处编写的内容确实是您想要执行的操作(即编写
file_len * (file_len - 1) + 1
行?),那么也许您应该将文件保存到列表中。另外,您没有在文件名周围加上引号,并且您的缩进很奇怪。试试这个:也许您实际上并不想要嵌套循环?
I don't quite follow your question. But I see several errors in your code. Most importantly:
Once you read a file, it's gone. (You can get it back, but in this case there's no point.) That means that the second call to
readlines
is yielding nothing, solen(infile.readlines()) == 0
. Assuming what you've written here really is what you want to do (i.e. writefile_len * (file_len - 1) + 1
lines?) then perhaps you should save the file to a list. Also, you didn't put quotes around your filenames, and your indentation is strange. Try this:Perhaps you don't actually want nested loops?