繁体   English   中英

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

[英]Python - variable inside for loop disappears outside of loop

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

我正在制作一个非常简单的 Python 脚本来合并几个 markdown 文件,同时保留所有换行符。 我要合并的文件称为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)

该变量仅返回第 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM