简体   繁体   中英

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. 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/ .

This is the text content of simple1.md :

Page 1

This is some useless content

This is the text content of simple2.md :

Page 2

This is some useless content

This is the text content of 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:

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

I would appreciate any help on this issue.

You're re-declaring the file variable inside the loop. 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

# 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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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