用变量在python中打开和读取文件

时间:2015-04-16 18:55:17

标签: python macos file

我的代码:

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


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

readfile()

在文件hello.c中:

#include <stdio.h>

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

我尝试将文件读入变量然后打印出来...... 它写了这个东西:

} printf("Hello World!");

我知道这可能是一些愚蠢的错误(我是初学者)..为什么它不打印所有文件?你能帮忙吗?

1 个答案:

答案 0 :(得分:1)

由于打印了“}”和“printf”,所以在我看来你的整个文件正在打印,但是所有在一行上 - 光标只返回到当前的开头用新数据划分并覆盖旧数据。

如果文件中的所有行都以回车符结束而不是换行符,则可能会发生这种情况。最简单的解决方案是使用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()

您也可以在通用换行模式下打开文件,该模式会将\ r转换为\ n。但是这种行为已被弃用,并将在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()