我正在尝试创建一个输出文件,以便在类项目中使用,但它会在此行上扫描字符串文字时继续提供EOL:outfile = open(r'C:\Users\kay\Documents\CCA Classes\CIS 119\numbers.txt', 'w')
。我知道“\”是一个特殊字符,但我的书中说r前缀使它成为一个原始字符串,应该将其作为文件位置。我做错了什么?
#This program creates the number file
import os
def main():
#Get how many numbers from the user
many_num = int(input("Enter how many numbers ' + \
you will be adding: '))
#Open a file for writing
outfile = open(r'C:\Users\kay\Documents\CCA Classes\CIS 119\numbers.txt', 'w'")
#Get the numbers and write to the file
for count in range(1,many-num +1):
numbers = int(input('Enter a number: ' + \
str(count) + ': '))
#write number to file
outfile.write(str(numbers) + '\n')
#Close the file
outfile.close()
print('Data written to numbers.txt.')
#Call main function
main()
答案 0 :(得分:2)
比较这两行,第二行是正确的(你可以使用双引号或单引号,这很重要)。通过使用双引号,您将两个参数作为一个字符串传递,其中包含单引号和逗号:
#outfile = open(r"C:\Python33\numbers.txt', 'w'")
outfile = open(r'C:\Python33\numbers.txt', 'w')