Python 3.x 如何使python程序编写新文件
我正在编写一个程序,通过它我可以从一个文件中提取数据,然后根据某种条件,我必须将该数据写入其他文件。这些文件不存在,只有代码将创建这些新文件。我尝试了各种可能的打印参数组合,但没有任何效果。程序似乎运行良好,空闲时没有错误,但没有创建新文件。有人能给我一个解决办法吗 这是我的密码:Python 3.x 如何使python程序编写新文件,python-3.x,persistence,Python 3.x,Persistence,我正在编写一个程序,通过它我可以从一个文件中提取数据,然后根据某种条件,我必须将该数据写入其他文件。这些文件不存在,只有代码将创建这些新文件。我尝试了各种可能的打印参数组合,但没有任何效果。程序似乎运行良好,空闲时没有错误,但没有创建新文件。有人能给我一个解决办法吗 这是我的密码: try: data= open('sketch.txt') for x in data: try: (person, sentence)= x.split(':
try:
data= open('sketch.txt')
for x in data:
try:
(person, sentence)= x.split(':',1)"""data is in form of sentences with: symbol present"""
man=[] # list to store person
other=[] #list to store sentence
if person=="Man":
man.append(sentence)
elif person=="Other Man":
other.append(sentence)
except ValueError:
pass
data.close()
except IOError:
print("file not found")
try:
man_file=open("man_file.txt","w")""" otherman_file and man_file are for storing data"""
otherman_file=open("otherman_file.txt", "w")
print(man,file= man_file.txt)
print(other, file=otherman_file.txt)
man_file.close()
otherman_file.close()
except IOError:
print ("file error")
2个问题
man_file = open("man_file.txt", "w+")
otherman_file = open("otherman_file.txt", "w+")
def func():
man = [] # list to store person
other = [] # list to store sentence
try:
data = open('sketch.txt', 'r')
for x in data:
try:
(person, sentence) = x.split(':', 1)
if person == "Man":
man.append(sentence)
elif person == "Other Man":
other.append(sentence)
except ValueError:
pass
data.close()
except IOError:
print("file not found")
try:
man_file = open("man_file.txt", "w+")
otherman_file = open("otherman_file.txt", "w+")
# print(man, man_file.txt)
# print(other, otherman_file.txt)
man_file.close()
otherman_file.close()
except IOError:
print ("file error")
func()
请添加sketch.txt数据格式这是我的sketch.txt-1。男:这是争论的地方吗?另一个男人:我告诉过你一次。男人:不,你没有!其他男人:是的,我有。男:什么时候?6.另一个男人:刚才。第二个字母的缩进好像不对。我是新来的,所以只是习惯一下。顺便说一句,我的空闲内存中没有缩进错误。它就发生在这里。我现在改进了我的缩进here@Naor你能用我的sketch.txt检查一下吗given@rachitsaini让我知道这是否对你有帮助这是我的sketch.txt-1男:这是争论的地方吗?另一个男人:我告诉过你一次。男人:不,你没有!其他男人:是的,我有。男:什么时候?6.另一个男人:刚才。我也试过r+,w+,a+,但它们似乎也不起作用。是否有一些管理员权限不允许这种情况发生?您使用哪个操作系统?我有一种奇怪的感觉,该文件已创建,但不在当前目录中,该脚本正在运行Windows 7 64位。我是否应该为新文件man_file.txt和otherman_file.txt提供完整的路径请对该文件进行简单搜索
def func():
man = [] # list to store person
other = [] # list to store sentence
try:
data = open('sketch.txt', 'r')
for x in data:
try:
(person, sentence) = x.split(':', 1)
if person == "Man":
man.append(sentence)
elif person == "Other Man":
other.append(sentence)
except ValueError:
pass
data.close()
except IOError:
print("file not found")
try:
man_file = open("man_file.txt", "w+")
otherman_file = open("otherman_file.txt", "w+")
# print(man, man_file.txt)
# print(other, otherman_file.txt)
man_file.close()
otherman_file.close()
except IOError:
print ("file error")
func()