Search code examples
pythonfor-loopmerge-file

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.


Solution

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