Python - for 循环内的变量在循环外消失

Python - variable inside for loop disappears outside of loop

编辑:如果您也遇到过这个问题,下面有两种可能的解决方案。

我正在制作一个非常简单的 Python 脚本来将多个降价文件合并在一起,同时保留所有换行符。我要合并的文件名为 markdown/simple1.mdmarkdown/simple2.mdmarkdown/simple3.md(它们位于名为 markdown/.

的文件夹中

这是simple1.md的文字内容:

Page 1

This is some useless content

这是simple2.md的文字内容:

Page 2

This is some useless content

这是simple3.md的文字内容:

Page 3

This is some useless content

这是我目前的情况:

# 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)

这非常有效。但是,一旦我尝试在 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)

变量只returns第3个markdown文件,不显示合并后的文件。

对于这个问题,我将不胜感激。

您正在循环内重新声明 file 变量。尝试:

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)

您需要实际合并文件内容 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)