1

my code:

#!/usr/bin/python3
import getopt
import sys
import re


def readfile():
    with open("hello.c", "r")  as myfile:
            data=myfile.read()
    print data

readfile()

in file hello.c:

#include <stdio.h>

void main()
{
    auto
    printf("Hello World!");
}

I try to read file into variable and then printout it... it writes this thing:

} printf("Hello World!");

I know it's probably some stupid error(I'm beginner)..WHY it doesn't print all the file? can you help?

1
  • 1
    I just copy-pasted both sources and worked just fine. Python2.7 though. Is your console working fine? Maybe it is something python3 related... But I suspect the console Commented Apr 16, 2015 at 19:25

1 Answer 1

1

Since both "}" and "printf" are printed, it looks to me like your whole file is being printed, but all on one line - the cursor just returns to the beginning of the current line and overwrites old data with new data.

This might happen if all of the lines in your file end with carriage returns and not newlines. The simplest solution would be to put the newlines where they belong using replace.

#!/usr/bin/python3
import getopt
import sys
import re


def readfile():
    with open("hello.c", "r")  as myfile:
            data=myfile.read().replace("\r", "\n")
    print data

readfile()

You could also open the file in universal newlines mode, which converts \r to \n for you. But this behavior is deprecated and will disappear in Python 4.0.

#!/usr/bin/python3
import getopt
import sys
import re


def readfile():
    with open("hello.c", "Ur")  as myfile:
            data=myfile.read()
    print data

readfile()
Sign up to request clarification or add additional context in comments.

3 Comments

OP could print(repr(data)) to see what is in the file.
@Kevin thank you, that's what I wanted...but is there any possibility to edit every single line of that file(e.g. for regex matching, replacing by substrings) ?
If you're asking "how do I iterate over the file line by line?", then do for line in file: or lines = file.readlines(). If you're asking "How do I make changes to the file?", you need to read the file into a string or list, make changes to that object, then open the file again in "w" mode and write your data back in.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.