我的代码:
#!/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!");
我知道这可能是一些愚蠢的错误(我是初学者)..为什么它不打印所有文件?你能帮忙吗?
最佳答案
由于“}”和“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()
关于python - 使用变量在 python 中打开和读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29683618/