[英]Python - variable inside for loop disappears outside of loop
EDIT: If you have also encountered this issue, there are two possible solutions below.编辑:如果您也遇到过这个问题,下面有两种可能的解决方案。
I am making a very simple Python script to merge several markdown files together, while preserving all line breaks.我正在制作一个非常简单的 Python 脚本来合并几个 markdown 文件,同时保留所有换行符。 The files I want to merge are called
markdown/simple1.md
, markdown/simple2.md
, and markdown/simple3.md
(they are placed inside a folder called markdown/
.我要合并的文件称为
markdown/simple1.md
、 markdown/simple2.md
和markdown/simple3.md
(它们位于名为markdown/
的文件夹中。
This is the text content of simple1.md
:这是
simple1.md
的文本内容:
Page 1
This is some useless content
This is the text content of simple2.md
:这是
simple2.md
的文本内容:
Page 2
This is some useless content
This is the text content of simple3.md
:这是
simple3.md
的文本内容:
Page 3
This is some useless content
And here is what I have so far:这是我到目前为止所拥有的:
# Define files I want to merge
filenames = ['markdown/simple1.md', 'markdown/simple2.md', 'markdown/simple3.md']
# Merge markdown files into one big file
merged_filecontent = ""
file = ""
for file in filenames:
file = open(file).read()
file += "\n"
# print(file)
merged_filecontent = file
print(merged_filecontent)
This works perfectly.这完美地工作。 However, as soon as I try to call a variable outside of my
for
loop, like this:但是,一旦我尝试在
for
循环之外调用变量,如下所示:
# Define files I want to merge
filenames = ['markdown/simple1.md', 'markdown/simple2.md', 'markdown/simple3.md']
# Merge markdown files into one big file
merged_filecontent = ""
file = ""
for file in filenames:
file = open(file).read()
file += "\n"
# print(file)
merged_filecontent = file
# Call variable outside of for loop
print(merged_filecontent)
The variable only returns the 3rd markdown file, and doesn't show the merged file.该变量仅返回第 3 个 markdown 文件,并且不显示合并后的文件。
I would appreciate any help on this issue.我将不胜感激有关此问题的任何帮助。
You're re-declaring the file
variable inside the loop.您正在循环内重新声明
file
变量。 Try:尝试:
filenames = ['markdown/simple1.md', 'markdown/simple2.md', 'markdown/simple3.md']
merged_filecontent = ""
for file in filenames:
with open(file) as f:
merged_filecontent += f.read()+"\n"
print(merged_filecontent)
You need to actually merge the file content with merged_filecontent += file
您实际上需要将文件内容与
merged_filecontent += file
合并
# Define files I want to merge
filenames = ['markdown/simple1.md', 'markdown/simple2.md', 'markdown/simple3.md']
# Merge markdown files into one big file
merged_filecontent = ""
file = ""
for file in filenames:
file = open(file).read()
file += "\n"
# print(file)
merged_filecontent += file
# Call variable outside of for loop
print(merged_filecontent)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.