JS4137
JS4137

Reputation: 406

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.

Upvotes: -1

Views: 408

Answers (2)

Rifat Bin Reza
Rifat Bin Reza

Reputation: 2781

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)

Upvotes: 1

Pedro Lobito
Pedro Lobito

Reputation: 99011

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)

Upvotes: 1

Related Questions