[英]Printing to a file via Python
Hopefully this is an easy fix. 希望这是一个简单的解决方法。 I'm trying to edit one field of a file we use for import, however when I run the following code it leaves the file blank and 0kb.
我正在尝试编辑用于导入的文件的一个字段,但是,当我运行以下代码时,它将文件保留为空白和0kb。 Could anyone advise what I'm doing wrong?
谁能告诉我我在做什么错?
import re #import regex so we can use the commands
name = raw_input("Enter filename:") #prompt for file name, press enter to just open test.nhi
if len(name) < 1 : name = "test.nhi"
count = 0
fhand = open(name, 'w+')
for line in fhand:
words = line.split(',') #obtain individual words by using split
words[34] = re.sub(r'\D', "", words[34]) #remove non-numeric chars from string using regex
if len(words[34]) < 1 : continue # If the 34th field is blank go to the next line
elif len(words[34]) == 2 : "{0:0>3}".format([words[34]]) #Add leading zeroes depending on the length of the field
elif len(words[34]) == 3 : "{0:0>2}".format([words[34]])
elif len(words[34]) == 4 : "{0:0>1}".format([words[34]])
fhand.write(words) #write the line
fhand.close() # Close the file after the loop ends
The file mode 'w+'
Truncates your file to 0 bytes, so you'll only be able to read lines that you've written. 文件模式
'w+'
将文件截断为0个字节,因此您将只能读取已写的行。
Look at Confused by python file mode "w+" for more information. 有关更多信息,请参见由python文件模式“ w +”引起的混淆 。
An idea would be to read the whole file first, close it, and re-open it to write files in it. 一个想法是先读取整个文件,将其关闭,然后重新打开以在其中写入文件。
I have taken below text in 'a.txt' as input and modified your code. 我已将“ a.txt”中的文本作为输入并修改了您的代码。 Please check if it's work for you.
请检查是否适合您。
#Intial Content of a.txt
This,program,is,Java,program
This,program,is,12Python,programs
Modified code as follow: 修改后的代码如下:
import re
#Reading from file and updating values
fhand = open('a.txt', 'r')
tmp_list=[]
for line in fhand:
#Split line using ','
words = line.split(',')
#Remove non-numeric chars from 34th string using regex
words[3] = re.sub(r'\D', "", words[3])
#Update the 3rd string
# If the 3rd field is blank go to the next line
if len(words[3]) < 1 :
#Removed continue it from here we need to reconstruct the original line and write it to file
print "Field empty.Continue..."
elif len(words[3]) >= 1 and len(words[3]) < 5 :
#format won't add leading zeros. zfill(5) will add required number of leading zeros depending on the length of word[3].
words[3]=words[3].zfill(5)
#After updating 3rd value in words list, again creating a line out of it.
tmp_str = ",".join(words)
tmp_list.append(tmp_str)
fhand.close()
#Writing to same file
whand = open("a.txt",'w')
for val in tmp_list:
whand.write(val)
whand.close()
File content after running code 运行代码后的文件内容
This,program,is,,program
This,program,is,00012,programs
Not sure which OS you're on but I think reading and writing to the same file has undefined behaviour. 不确定您使用的是哪个操作系统,但我认为读写同一文件具有不确定的行为。
I guess internally the file object holds the position (try fhand.tell()
to see where it is). 我猜在文件对象内部保持位置(尝试
fhand.tell()
看看它在哪里)。 You could probably adjust it back and forth as you went using fhand.seek(last_read_position)
but really that's asking for trouble. 您可能会在使用
fhand.seek(last_read_position)
来回调整它,但实际上这很麻烦。
Also, I'm not sure how the script would ever end as it would end up reading the stuff it had just written (in a sort of infinite loop). 另外,我不确定脚本的结局如何,因为脚本最终会读取它刚刚编写的内容(在某种无限循环中)。
Best bet is to read the entire file first: 最好的选择是先读取整个文件:
with open(name, 'r') as f:
lines = f.read().splitlines()
with open(name, 'w') as f:
for l in lines:
# ....
f.write(something)
For ' Printing to a file via Python ' you can use: 对于“ 通过Python打印到文件 ”,您可以使用:
ifile = open("test.txt","r")
print("Some text...", file = ifile)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.